Java 类org.apache.http.ParseException 实例源码

项目:lams    文件:NetscapeDraftHeaderParser.java   
public HeaderElement parseHeader(
        final CharArrayBuffer buffer,
        final ParserCursor cursor) throws ParseException {
    if (buffer == null) {
        throw new IllegalArgumentException("Char array buffer may not be null");
    }
    if (cursor == null) {
        throw new IllegalArgumentException("Parser cursor may not be null");
    }
    NameValuePair nvp = parseNameValuePair(buffer, cursor);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    while (!cursor.atEnd()) {
        NameValuePair param = parseNameValuePair(buffer, cursor);
        params.add(param);
    }
    return new BasicHeaderElement(
            nvp.getName(),
            nvp.getValue(), params.toArray(new NameValuePair[params.size()]));
}
项目:lams    文件:EntityUtils.java   
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
项目:weixin_api    文件:MpDataCubeApi.java   
/**
 * 获取接口分析小时数据。
 * 
 * @param date
 * @return
 * @throws AccessTokenFailException
 * @throws ParseException
 * @throws IOException
 * @throws URISyntaxException
 */
public DataCubeGetInterfaceSummaryHourResp apiDataCubeGetInterfaceSummaryHour(java.sql.Date date)
        throws AccessTokenFailException, ParseException, IOException, URISyntaxException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/datacube/getinterfacesummaryhour?access_token=%s", token.getAccessToken());
    TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
    reqMap.put("begin_date", date);
    reqMap.put("end_date", date);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    DataCubeGetInterfaceSummaryHourResp resp = new Gson().fromJson(respText,
            DataCubeGetInterfaceSummaryHourResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiDataCubeGetInterfaceSummaryHour %s", resp));
    }
    return resp;
}
项目:weixin_api    文件:MpWebApi.java   
/**
 * 刷新微信用户网页授权AccessToken。如果是开放平台模式则此方法内部会调用OpenApi中获取。
 * 由于此api使用频次比较低,因此未进行缓存,要求业务系统保存OAuthAccessToken,特别是其中的refresh_token。
 * 
 * @param refreshToken
 * @return
 * @throws AccessTokenFailException
 * @throws URISyntaxException
 * @throws IOException
 * @throws ParseException
 */
public OAuthAccessToken apiSnsOAuth2RefreshToken(String refreshToken)
        throws AccessTokenFailException, ParseException, IOException, URISyntaxException {
    if (mpApi.config.isOpenMode()) {// 公众平台模式
        return OpenApi.getInstance().apiSnsOAuth2ComponentRefreshToken(mpApi.appid, refreshToken);
    }
    String path = String.format("/oauth2/refresh_token?mpApi.appid=%s&grant_type=refresh_token&refresh_token=%s",
            mpApi.config.getAppId(), refreshToken);
    String respText = HttpUtil.get(mpApi.config.getApiOAuth(), path);
    OAuthAccessToken resp = new Gson().fromJson(respText, OAuthAccessToken.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiSnsOAuth2RefreshToken %s", resp));
    }
    return resp;

}
项目:weixin_api    文件:OpenApi.java   
/**
 * 获取微信用户网页授权AccessToken。
 * 由于此api使用频次比较低,因此要求业务系统保存OAuthAccessToken,特别是其中的refresh_token。
 * 如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止。
 * 
 * @param mpAppid
 * @param code
 * 
 * @return
 * @throws AccessTokenFailException
 * @throws URISyntaxException
 * @throws IOException
 * @throws ParseException
 */
public OAuthAccessToken apiSnsOAuth2ComponentAccessToken(String mpAppid, String code)
        throws AccessTokenFailException, ParseException, IOException, URISyntaxException {
    ComponentAccessToken caToken = apiComponentToken();
    String path = String.format(
            "/oauth2/component/access_token?appid=%s&code=%s&grant_type=authorization_code&component_appid=%s&component_access_token=%s",
            mpAppid, code, config.getComponentAppid(), caToken.getComponentAccessToken());

    String respText = HttpUtil.get(config.getApiOAuth(), path);
    OAuthAccessToken resp = new Gson().fromJson(respText, OAuthAccessToken.class);
    if (log.isInfoEnabled()) {
        log.info(String.format("apiOAuth2ComponentAccessToken %s", resp));
    }
    return resp;

}
项目:devops-cstack    文件:AbstractDeploymentControllerIT.java   
protected Optional<String> waitForContent(String url) {
    return Stream.generate(() -> {
                try {
                    Thread.sleep(1000);
                    System.out.println(url);
                    return getUrlContentPage(url);
                } catch (ParseException | IOException | InterruptedException e) {
                    return null;
                } finally {

                }
            })
        .limit(TestUtils.NB_ITERATION_MAX)
        .filter(content -> content != null && !content.contains("404"))
        .findFirst();
}
项目:cloud-ariba-partner-flow-extension-ext    文件:HttpResponseUtils.java   
/**
 * Deserializes an HTTP response entity to a given class.
 * 
 * @param entity
 *            the HTTP response entity to be deserialized.
 * @param cls
 *            the target class.
 * @return the response deserialized to the target class.
 * @throws HttpResponseException
 *             when the response cannot be deserialized to the given entity
 *             class.
 */
static <T> T deserialize(HttpEntity entity, Class<T> cls) throws HttpResponseException {
    if (entity == null) {
        logger.error(ERROR_ENTITY_CANNOT_BE_NULL);

        throw new IllegalArgumentException(ERROR_ENTITY_CANNOT_BE_NULL);
    }

    T result = null;
    try {
        logger.debug(DEBUG_CONVERTING_HTTP_ENTITY);
        result = GsonProvider.getInstance().fromJson(EntityUtils.toString(entity, StandardCharsets.UTF_8), cls);
    } catch (ParseException | IOException e) {
        String errorMessage = MessageFormat
                .format(ERROR_PROBLEM_OCCURED_WHILE_CONVERTING_RESPONSE_ENTITY_TO_CLASS_MESSAGE, cls.getName());
        logger.error(errorMessage);
        throw new HttpResponseException(errorMessage, e);
    }

    logger.debug(DEBUG_CONVERTED_HTTP_ENTITY);
    return result;
}
项目:lams    文件:BasicHeaderValueParser.java   
/**
 * Parses elements with the given parser.
 *
 * @param value     the header value to parse
 * @param parser    the parser to use, or <code>null</code> for default
 *
 * @return  array holding the header elements, never <code>null</code>
 */
public final static
    HeaderElement[] parseElements(final String value,
                                  HeaderValueParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null");
    }

    if (parser == null)
        parser = BasicHeaderValueParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseElements(buffer, cursor);
}
项目:lams    文件:BasicHeaderValueParser.java   
/**
 * Parses an element with the given parser.
 *
 * @param value     the header element to parse
 * @param parser    the parser to use, or <code>null</code> for default
 *
 * @return  the parsed header element
 */
public final static
    HeaderElement parseHeaderElement(final String value,
                                     HeaderValueParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null");
    }

    if (parser == null)
        parser = BasicHeaderValueParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseHeaderElement(buffer, cursor);
}
项目:lams    文件:BasicHeaderValueParser.java   
/**
 * Parses parameters with the given parser.
 *
 * @param value     the parameter list to parse
 * @param parser    the parser to use, or <code>null</code> for default
 *
 * @return  array holding the parameters, never <code>null</code>
 */
public final static
    NameValuePair[] parseParameters(final String value,
                                    HeaderValueParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null");
    }

    if (parser == null)
        parser = BasicHeaderValueParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseParameters(buffer, cursor);
}
项目:lams    文件:BasicHeaderValueParser.java   
/**
 * Parses a name-value-pair with the given parser.
 *
 * @param value     the NVP to parse
 * @param parser    the parser to use, or <code>null</code> for default
 *
 * @return  the parsed name-value pair
 */
public final static
   NameValuePair parseNameValuePair(final String value,
                                    HeaderValueParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null");
    }

    if (parser == null)
        parser = BasicHeaderValueParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseNameValuePair(buffer, cursor);
}
项目:lams    文件:BasicTokenIterator.java   
/**
 * Determines the next token.
 * If found, the token is stored in {@link #currentToken}.
 * The return value indicates the position after the token
 * in {@link #currentHeader}. If necessary, the next header
 * will be obtained from {@link #headerIt}.
 * If not found, {@link #currentToken} is set to <code>null</code>.
 *
 * @param from      the position in the current header at which to
 *                  start the search, -1 to search in the first header
 *
 * @return  the position after the found token in the current header, or
 *          negative if there was no next token
 *
 * @throws ParseException   if an invalid header value is encountered
 */
protected int findNext(int from)
    throws ParseException {

    if (from < 0) {
        // called from the constructor, initialize the first header
        if (!this.headerIt.hasNext()) {
            return -1;
        }
        this.currentHeader = this.headerIt.nextHeader().getValue();
        from = 0;
    } else {
        // called after a token, make sure there is a separator
        from = findTokenSeparator(from);
    }

    int start = findTokenStart(from);
    if (start < 0) {
        this.currentToken = null;
        return -1; // nothing found
    }

    int end = findTokenEnd(start);
    this.currentToken = createToken(this.currentHeader, start, end);
    return end;
}
项目:lams    文件:BufferedHeader.java   
/**
 * Creates a new header from a buffer.
 * The name of the header will be parsed immediately,
 * the value only if it is accessed.
 *
 * @param buffer    the buffer containing the header to represent
 *
 * @throws ParseException   in case of a parse error
 */
public BufferedHeader(final CharArrayBuffer buffer)
    throws ParseException {

    super();
    if (buffer == null) {
        throw new IllegalArgumentException
            ("Char array buffer may not be null");
    }
    int colon = buffer.indexOf(':');
    if (colon == -1) {
        throw new ParseException
            ("Invalid header: " + buffer.toString());
    }
    String s = buffer.substringTrimmed(0, colon);
    if (s.length() == 0) {
        throw new ParseException
            ("Invalid header: " + buffer.toString());
    }
    this.buffer = buffer;
    this.name = s;
    this.valuePos = colon + 1;
}
项目:lams    文件:BasicLineParser.java   
public final static
    ProtocolVersion parseProtocolVersion(String value,
                                         LineParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null.");
    }

    if (parser == null)
        parser = BasicLineParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseProtocolVersion(buffer, cursor);
}
项目:lams    文件:BasicLineParser.java   
public final static
    RequestLine parseRequestLine(final String value,
                                 LineParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null.");
    }

    if (parser == null)
        parser = BasicLineParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseRequestLine(buffer, cursor);
}
项目:lams    文件:BasicLineParser.java   
public final static
    StatusLine parseStatusLine(final String value,
                               LineParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null.");
    }

    if (parser == null)
        parser = BasicLineParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseStatusLine(buffer, cursor);
}
项目:lams    文件:BasicLineParser.java   
public final static
    Header parseHeader(final String value,
                       LineParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null");
    }

    if (parser == null)
        parser = BasicLineParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    return parser.parseHeader(buffer);
}
项目:kowalski    文件:Dependent.java   
public Page<URI, Artifact> fetchPage(URI uri)
        throws ClientProtocolException, IOException, URISyntaxException, ParseException, NotOkResponseException {
    HttpGet request = new HttpGet(uri);
    try (CloseableHttpResponse response = this.client.execute(request)) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return new Page<>(Optional.empty(), Collections.emptyList());
        }
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new NotOkResponseException(
                    String.format("Service response not ok %s %s %s", response.getStatusLine(),
                            response.getAllHeaders(), EntityUtils.toString(response.getEntity())));
        }
        Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()), uri.toString());
        Optional<URI> next = Optional.empty();
        Elements nexts = document.select(".search-nav li:last-child a[href]");
        if (!nexts.isEmpty()) {
            next = Optional.of(new URI(nexts.first().attr("abs:href")));
        }
        List<Artifact> artifacts = document.select(".im .im-subtitle").stream()
                .map(element -> new DefaultArtifact(element.select("a:nth-child(1)").first().text(),
                        element.select("a:nth-child(2)").first().text(), null, null))
                .collect(Collectors.toList());
        return new Page<>(next, artifacts);
    }
}
项目:LearningSummary    文件:HttpRequestUtil.java   
public static void main(String[] args) throws ParseException, IOException {
    HttpRequestUtil util = new HttpRequestUtil();
    CloseableHttpClient client = util.setDoubleInit();

    Map<String,String> map = new HashMap<>();
    CloseableHttpResponse httpPost = util.httpPost(client, "https://127.0.0.1:8443/pwp-web/login.do", map);

    HttpEntity entity = httpPost.getEntity();
    String string = EntityUtils.toString(entity, Charset.defaultCharset());

    System.out.println(string);
}
项目:bubble2    文件:ResponseWrap.java   
/**
 * 获取响应内容为字节数组
 * 
 * 
 * @date 2015年7月17日
 * @return
 */
public byte[] getByteArray() {
    try {
        return EntityUtils.toByteArray(entity);
    } catch (ParseException | IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
}
项目:cloud-ariba-discovery-rfx-to-external-marketplace-ext    文件:HttpResponseUtils.java   
/**
 * Converts an HTTP response entity to a given class.
 * 
 * @param entity
 *            the HTTP response entity to be converted.
 * @param cls
 *            the target class.
 * @return the response converted to the target class.
 * @throws HttpResponseException
 *             when the response cannot be converted to the given entity
 *             class.
 */
public static <T> T convertHttpResponse(HttpEntity entity, Class<T> cls) throws HttpResponseException {
    if (entity == null) {
        logger.error(ERROR_ENTITY_CANNOT_BE_NULL);

        throw new IllegalArgumentException(ERROR_ENTITY_CANNOT_BE_NULL);
    }

    T result = null;
    try {
        logger.debug(DEBUG_CONVERTING_HTTP_ENTITY);
        result = gson.fromJson(EntityUtils.toString(entity, StandardCharsets.UTF_8), cls);
    } catch (ParseException | IOException e) {
        String errorMessage = MessageFormat
                .format(ERROR_PROBLEM_OCCURED_WHILE_CONVERTING_RESPONSE_ENTITY_TO_CLASS_MESSAGE, cls.getName());
        logger.error(errorMessage);
        throw new HttpResponseException(errorMessage, e);
    }

    logger.debug(DEBUG_CONVERTED_HTTP_ENTITY);
    return result;
}
项目:parent    文件:HttpClientUtil.java   
public static void main(String[] args) throws ParseException, IOException {
    /*
     * String url = "https://api.weixin.qq.com/cgi-bin/token";
     * List<NameValuePair> formparams = new ArrayList<NameValuePair>();
     * formparams.add(new BasicNameValuePair("grant_type",
     * "client_credential")); formparams.add(new BasicNameValuePair("appid",
     * "wxae034fc58441d7b2")); formparams.add(new
     * BasicNameValuePair("secret", "c9813bc84a3032622dc4178e01c0bd75"));
     * 
     * String body =HttpClentUtil.httpGet(url, formparams);
     * 
     * log.info(body);
     */

    String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=S9STXzYKfiNH-y9CCt1CpdnpHZWkNgRQwrhRkMzF8ZZY-NhgOHyBci9sfVHLLH6zCG0GnZqNkZTNzmyJkrI2NvPUswNbE8tv67ImhKwc5imz1kYX8RWGwEDzI4qzLhl2WOXjACAGYH";
    String body = "{\"button\":[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"},{\"name\":\"菜单\",\"sub_button\":[{\"type\":\"view\",\"name\": \"搜索\",\"url\":\"http://www.soso.com/\"}]}]}";
    // System.out.println(HttpClentUtil.doPostStr(url, body));
    System.out.println(HttpClientUtil.httpPost(url, body));

}
项目:phoenix.interface.framework    文件:SimpleHttpClient.java   
public String executeJsonPost(String url, JSON jsonObj) throws ParseException, IOException
{
    if(url.startsWith("/"))
    {
        url = host + url;
    }

    HttpPost post = new HttpPost(url);

    StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
    entity.setContentType("application/json");

    post.setEntity(entity);

    return fetchReponseText(post);
}
项目:phoenix.interface.framework    文件:WebDriverApiTest.java   
@Test
    public void findElement() throws ParseException, IOException
    {
//        res = client.executePost("/session/" + sessionId + "/timeouts", null);
//        System.out.println("set timeouts" + res);

//        res = client.executeGet("/session/" + sessionId + "/timeouts");
//        System.out.println("timeouts : " + res);
        Map<String, String> param = new HashMap<String, String>();
        param.put("using", "id");
        param.put("value", "content-sidebar");

        String res = client.executePost("/session/" + sessionId + "/element", param, true);
        System.out.println("find element : " + res);

        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = (JsonObject) jsonParser.parse(res);

        String elementId = jsonObject.get("value").getAsJsonObject().get("ELEMENT").getAsString();

        getAttribute(elementId);
        getCss(elementId);
        isSelected(elementId);
        elementEnabled(elementId);
    }
项目:eSDK_EC_SDK_Java    文件:RestfulAdapterImplHttpClient.java   
private Object postSend(HttpResponse response, String resObjClass)
    throws ProtocolAdapterException, ParseException, IOException
{
    HttpEntity entity = response.getEntity();
    String responsePayload = EntityUtils.toString(entity);

    if (null != sdkProtocolAdatperCustProvider)
    {
        sdkProtocolAdatperCustProvider.postSend(responsePayload);
        return sdkProtocolAdatperCustProvider.postBuildRes(responsePayload, resObjClass);
    }
    else
    {
        // Process the response body
        LOGGER.debug("The response content is:" + response);
        return responsePayload;
    }
}
项目:eSDK_EC_SDK_Java    文件:RestfulAdapterImplHttpClientHTLS.java   
private Object postSend(HttpResponse response, String resObjClass)
    throws ProtocolAdapterException, ParseException, IOException
{
    HttpEntity entity = response.getEntity();
    String responsePayload = EntityUtils.toString(entity);

    if (null != sdkProtocolAdatperCustProvider)
    {
        sdkProtocolAdatperCustProvider.postSend(responsePayload);
        return sdkProtocolAdatperCustProvider.postBuildRes(responsePayload, resObjClass);
    }
    else
    {
        // Process the response body
        LOGGER.debug("The response content is:" + response);
        return responsePayload;
    }
}
项目:amex-api-java-client-core    文件:ApiClientResponseTest.java   
@Test
public void valid() {
    Header[] headers = {new Header() {
        public String getName() {
            return "session_id";
        }

        public String getValue() {
            return "12345";
        }

        public HeaderElement[] getElements() throws ParseException {
            return new HeaderElement[0];
        }
    }};
    ApiClientResponse response = new ApiClientResponse(headers, "{\"key\":\"value\"}");

    assertEquals("12345", response.getHeader("session_id"));
    assertEquals("{\n  \"key\" : \"value\"\n}", response.toJson());
    assertEquals("value", response.getField("key"));
}
项目:eSDK_IVS_Java    文件:RestfulAdapterImplHttpClient.java   
private Object postSend(HttpResponse response, String resObjClass)
    throws ProtocolAdapterException, ParseException, IOException
{
    HttpEntity entity = response.getEntity();
    String responsePayload = EntityUtils.toString(entity);

    if (null != sdkProtocolAdatperCustProvider)
    {
        sdkProtocolAdatperCustProvider.postSend(responsePayload);
        return sdkProtocolAdatperCustProvider.postBuildRes(responsePayload, resObjClass);
    }
    else
    {
        // Process the response body
        LOGGER.debug("The response content is:" + response);
        return responsePayload;
    }
}
项目:eSDK_IVS_Java    文件:RestfulAdapterImplHttpClientHTLS.java   
private Object postSend(HttpResponse response, String resObjClass)
    throws ProtocolAdapterException, ParseException, IOException
{
    HttpEntity entity = response.getEntity();
    String responsePayload = EntityUtils.toString(entity);

    if (null != sdkProtocolAdatperCustProvider)
    {
        sdkProtocolAdatperCustProvider.postSend(responsePayload);
        return sdkProtocolAdatperCustProvider.postBuildRes(responsePayload, resObjClass);
    }
    else
    {
        // Process the response body
        LOGGER.debug("The response content is:" + response);
        return responsePayload;
    }
}
项目:remote-files-sync    文件:EntityUtilsHC4.java   
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    Args.notNull(entity, "Entity");
    String charset = null;
    if (entity.getContentType() != null) {
        final HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            final NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
项目:printos-device-api-example-java    文件:Device.java   
public static boolean postRealTimeData(HttpClient client, String url, String deviceToken) throws ParseException, IOException {
  HttpPost post = new HttpPost(url);
  post.addHeader("Cookie", Constants.X_SMS_AUTH_TOKEN + "=" + deviceToken);

  long MINS_AHEAD = 1000 * 60 * 30;   // Pretend we have 30 minutes of print time left
  int jobsInQueue = 6;                // and 6 jobs left in the queue
  String status = "DS_PRINTING";      // and we're currently printing

  Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  Timestamp printCompleteTime = new Timestamp(cal.getTime().getTime() + MINS_AHEAD);
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  String date = format.format(printCompleteTime.getTime());

  ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
  ObjectNode jsonNode = mapper.createObjectNode();

  jsonNode.put("deviceStatus", status);
  jsonNode.put("totalJobs", jobsInQueue);
  jsonNode.put("printTimeComplete", date);

  StringEntity entity = new StringEntity(jsonNode.toString());
  post.setEntity(entity);

  HttpResponse response = HttpClientWrapper.executeHttpCommand(client, post);
  if (response != null) {
    if (response.getStatusLine().getStatusCode() != 204) {
      HttpClientWrapper.logErrorResponse(response, "Failed To post data");
      return false;
    } else {
      EntityUtils.consumeQuietly(response.getEntity());
      log.info("Sucessfully posted data");
      System.out.println("Successfully posted data.");
      return false;
    }
  } else {
    log.error("No response returned from post data");
    return false;
  }
}
项目:printos-device-api-example-java    文件:User.java   
public static String loginAndGetToken(HttpClient client, String url, String login, String password)
  throws ParseException, IOException
{
  String token = null;
  HttpPost loginPost = new HttpPost(url);

  ObjectMapper mapper = new ObjectMapper();
  ObjectNode jsonNode = mapper.createObjectNode();

  jsonNode.put("login", login);
  jsonNode.put("password", password);

  StringEntity entity = new StringEntity(jsonNode.toString());
  loginPost.setEntity(entity);

  HttpResponse response = HttpClientWrapper.executeHttpCommand(client, loginPost);
  if (response != null)
  {
    if(response.getStatusLine().getStatusCode() == 200)
    {
      token = HttpClientWrapper.getTokenFromResponse(response);
      EntityUtils.consumeQuietly(response.getEntity());
    }
    else {
      HttpClientWrapper.logErrorResponse(response, "Failed To login");
    }
  }else {
    log.error("No response returned from login call");
  }

  return token;
}
项目:vespa    文件:ApacheGatewayConnectionTest.java   
private void addMockedHeader(
        final HttpResponse httpResponseMock,
        final String name,
        final String value,
        HeaderElement[] elements) {
    final Header header = new Header() {
        @Override
        public String getName() {
            return name;
        }
        @Override
        public String getValue() {
            return value;
        }
        @Override
        public HeaderElement[] getElements() throws ParseException {
            return elements;
        }
    };
    when(httpResponseMock.getFirstHeader(name)).thenReturn(header);
}
项目:Visit    文件:EntityUtilsHC4.java   
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    Args.notNull(entity, "Entity");
    String charset = null;
    if (entity.getContentType() != null) {
        final HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            final NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
项目:mobile-android-studio    文件:ExoUtils.java   
/**
 * Removes unnecessary parts of the given URL.<br/>
 * The returned URL has the format: http(s)://host(:port)
 * 
 * @param url The URL to reformat.
 * @return The reformatted URL.
 */
public static String stripUrl(String url) {
  String sUrl;
  try {
    ExoWebAddress webaddress = new ExoWebAddress(url);
    String scheme = webaddress.getScheme();
    String host = webaddress.getHost();
    int portNumber = webaddress.getPort();
    String port = "";
    if (portNumber != -1) {
      port = ":" + Integer.toString(portNumber);
    }
    sUrl = scheme + "://" + host + port;
  } catch (ParseException pe) {
    sUrl = null;
  }
  return sUrl;
}
项目:WeChatServer    文件:MessageUtils.java   
/**
 * ͨ���زĹ���ӿ��ϴ�ͼƬ�ļ����õ���id��
 * 
 * @param filePath
 *            ͼƬ�ļ�·��
 * @return
 * @throws IOException
 * @throws ParseException
 */
private static String upload(String filePath) throws ParseException,
        IOException {

    AccessToken token = AccessTokenUtils.getAccessToken();
    System.out.println(token.getToken());
    String MediaId = null;
    try {
        MediaId = WeChatUtils.upload(filePath, token.getToken(), "image");
        System.out.println("�ϴ��ɹ�");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("�ϴ�ʧ��");
    }
    return MediaId;
}
项目:tool.lars    文件:RepositoryContext.java   
private void assertStatusCode(int expectedStatusCode, HttpResponse response) throws ParseException, IOException {
    StatusLine statusLine = response.getStatusLine();

    int actualStatusCode = statusLine.getStatusCode();

    boolean statusCodeMatches = expectedStatusCode == actualStatusCode
                                || (expectedStatusCode == RC_REJECT && (actualStatusCode == 403 || actualStatusCode == 401));

    if (!statusCodeMatches) {
        String failMessage = "Unexpected status code: " + actualStatusCode + "; expected: " + expectedStatusCode + "\n";
        failMessage += "Full HTTP response:";
        try {
            failMessage += EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch (UnsupportedEncodingException e) {
            failMessage += "Unable to get full HTTP response!";

        }

        fail(failMessage);
    }
}
项目:netflixbmc    文件:NetflixClientImpl.java   
private String getAuthUrl() throws ParseException, IOException, InterruptedException {
    Elements elements = null;
    String authUrl = null;

    //Netflix sometimes sends "BLOCKED", just try again
    int i = 0;
    while (i++ < MAX_AUTH_PAGE_RETRIES) {
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        HttpGet get = new HttpGet(LOGIN_URL);
        HttpResponse response = client.execute(get, localContext);
        String html = EntityUtils.toString(response.getEntity());

        Document doc = Jsoup.parse(html, LOGIN_URL);
        elements = doc.getElementsByAttributeValue("name", "authURL");
        if(elements != null && elements.size() > 0) {
            authUrl = elements.first().attr("value");
            break;
        } else {
            Thread.sleep(1000);
        }
    }

    return authUrl;
}
项目:dbod-webapp    文件:RestHelper.java   
public static <T> T getObjectListFromRestApi(String path, Class<T> object) {
    Gson gson = init();

    try {
        HttpClient httpclient = HttpClientBuilder.create().build();

        HttpGet request = new HttpGet(ConfigLoader.getProperty(CommonConstants.DBOD_API_LOCATION) + path);
        HttpResponse response = httpclient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200)
        {
            String resp = EntityUtils.toString(response.getEntity());
            JsonElement json = parseList(resp);

            T result = gson.fromJson(json, object);
            EntityUtils.consume(response.getEntity());
            return result;
        }
    } catch (IOException | ParseException e) {
        Logger.getLogger(RestHelper.class.getName()).log(Level.SEVERE, null, e);
    }

    return null;
}
项目:FHIR-Server    文件:TinderJpaRestServerMojo.java   
public static void main(String[] args) throws ParseException, IOException, MojoFailureException, MojoExecutionException {

        // PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
        // HttpClientBuilder builder = HttpClientBuilder.create();
        // builder.setConnectionManager(connectionManager);
        // CloseableHttpClient client = builder.build();
        //
        // HttpGet get = new HttpGet("http://fhir.healthintersections.com.au/open/metadata");
        // CloseableHttpResponse response = client.execute(get);
        //
        // String metadataString = EntityUtils.toString(response.getEntity());
        //
        // ourLog.info("Metadata String: {}", metadataString);

        // String metadataString = IOUtils.toString(new FileInputStream("src/test/resources/healthintersections-metadata.xml"));
        // Conformance conformance = new FhirContext(Conformance.class).newXmlParser().parseResource(Conformance.class, metadataString);

        TinderJpaRestServerMojo mojo = new TinderJpaRestServerMojo();
        mojo.packageBase = "ca.uhn.test";
        mojo.baseResourceNames = java.util.Collections.singletonList("observation");
        mojo.targetDirectory = new File("target/generated/valuesets");
        mojo.execute();
    }