Java Code Examples for org.apache.http.entity.ContentType#getCharset()

The following examples show how to use org.apache.http.entity.ContentType#getCharset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Http4FileContentInfoFactory.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    String contentMimeType = null;
    String contentCharset = null;

    try (final Http4FileObject<Http4FileSystem> http4File = (Http4FileObject<Http4FileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        final HttpResponse lastHeadResponse = http4File.getLastHeadResponse();

        final Header header = lastHeadResponse.getFirstHeader(HTTP.CONTENT_TYPE);

        if (header != null) {
            final ContentType contentType = ContentType.parse(header.getValue());
            contentMimeType = contentType.getMimeType();

            if (contentType.getCharset() != null) {
                contentCharset = contentType.getCharset().name();
            }
        }

        return new DefaultFileContentInfo(contentMimeType, contentCharset);
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
}
 
Example 2
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static String contentAsString(URI uri, ProgressMonitor<Long> monitor) throws IOException {
   CloseableHttpResponse rsp = get(uri);
   try {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();
      ContentType ct = ContentType.get(entity);

      Charset cs = ct.getCharset();
      if (cs == null) cs = StandardCharsets.UTF_8;

      long length = entity.getContentLength();
      int clength = (int)length;
      if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;

      try (InputStream is = entity.getContent();
           ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
         copy(is, os, length, monitor);
         EntityUtils.consume(entity);
         return new String(os.toByteArray(), cs);
      }
   } finally {
      rsp.close();
   }
}
 
Example 3
Source File: DefaultDispatch.java    From knox with Apache License 2.0 6 votes vote down vote up
protected String getInboundResponseContentType( final HttpEntity entity ) {
  String fullContentType = null;
  if( entity != null ) {
    ContentType entityContentType = ContentType.get( entity );
    if( entityContentType != null ) {
      if( entityContentType.getCharset() == null ) {
        final String entityMimeType = entityContentType.getMimeType();
        final String defaultCharset = MimeTypes.getDefaultCharsetForMimeType( entityMimeType );
        if( defaultCharset != null ) {
          LOG.usingDefaultCharsetForEntity( entityMimeType, defaultCharset );
          entityContentType = entityContentType.withCharset( defaultCharset );
        }
      } else {
        LOG.usingExplicitCharsetForEntity( entityContentType.getMimeType(), entityContentType.getCharset() );
      }
      fullContentType = entityContentType.toString();
    }
  }
  if( fullContentType == null ) {
    LOG.unknownResponseEntityContentType();
  } else {
    LOG.inboundResponseEntityContentType( fullContentType );
  }
  return fullContentType;
}
 
Example 4
Source File: ResponseContentSupplier.java    From service-now-plugin with MIT License 6 votes vote down vote up
private void readCharset(HttpResponse response) {
    Charset charset = null;
    ContentType contentType = ContentType.get(response.getEntity());
    if (contentType != null) {
        charset = contentType.getCharset();
        if (charset == null) {
            ContentType defaultContentType = ContentType.getByMimeType(contentType.getMimeType());
            if (defaultContentType != null) {
                charset = defaultContentType.getCharset();
            }
        }
    }
    if (charset != null) {
        this.charset = charset.name();
    }
}
 
Example 5
Source File: LocalRestRequest.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public void setContent(final String source, final ContentType contentType) throws UnsupportedCharsetException {
    Args.notNull(source, "Source string");
    Charset charset = contentType != null?contentType.getCharset():null;
    if(charset == null) {
        charset = HTTP.DEF_CONTENT_CHARSET;
    }

    try {
        this.content = new BytesArray(source.getBytes(charset.name()));
    } catch (UnsupportedEncodingException var) {
        throw new UnsupportedCharsetException(charset.name());
    }

    if(contentType != null) {
        addHeader("Content-Type", contentType.toString());
    }
}
 
Example 6
Source File: ApacheHttpClient4Signer.java    From oauth1-signer-java with MIT License 6 votes vote down vote up
public void sign(HttpRequestBase req) throws IOException {
  String payload = null;
  Charset charset = Charset.defaultCharset();
  if (HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())) {
    HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) req;
    HttpEntity entity = requestBase.getEntity();
    if (entity.getContentLength() > 0) {
      if (!entity.isRepeatable()) {
        throw new IOException(
            "The signer needs to read the request payload but the input stream of this request cannot be read multiple times. Please provide the payload using a separate argument or ensure that the entity is repeatable.");
      }
      ContentType contentType = ContentType.get(entity);
      charset = contentType.getCharset();
      payload = EntityUtils.toString(entity, contentType.getCharset());
    }
  }

  String authHeader = OAuth.getAuthorizationHeader(req.getURI(), req.getMethod(), payload, charset, consumerKey, signingKey);
  req.setHeader(OAuth.AUTHORIZATION_HEADER_NAME, authHeader);
}
 
Example 7
Source File: CognalysVerifyClient.java    From tigase-extension with GNU General Public License v3.0 5 votes vote down vote up
private JsonObject _get(String url, List<NameValuePair> params) throws IOException {
    URI uri;
    try {
        uri = new URIBuilder(url)
                .addParameters(params)
                // add authentication parameters
                .addParameter("app_id", appId)
                .addParameter("access_token", token)
                .build();
    }
    catch (URISyntaxException e) {
        throw new IOException("Invalid URL", e);
    }
    HttpGet req = new HttpGet(uri);
    CloseableHttpResponse res = client.execute(req);
    try {
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            if (entity != null) {
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                if (charset == null)
                    charset = Charset.forName("UTF-8");
                Reader reader = new InputStreamReader(entity.getContent(), charset);
                return (JsonObject) new JsonParser().parse(reader);
            }

            // no response body
            return new JsonObject();
        }
        else
            throw new HttpResponseException(
                    res.getStatusLine().getStatusCode(),
                    res.getStatusLine().getReasonPhrase());
    }
    finally {
        res.close();
    }
}
 
Example 8
Source File: HttpResponseHandler.java    From iaf with Apache License 2.0 5 votes vote down vote up
public String getCharset() {
	ContentType contentType = getContentType();
	String charSet = Misc.DEFAULT_INPUT_STREAM_ENCODING;
	if(contentType != null && contentType.getCharset() != null)
		charSet = contentType.getCharset().displayName();
	return charSet;
}
 
Example 9
Source File: HubicAuthenticationResponseHandler.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AuthenticationResponse handleResponse(final HttpResponse response) throws IOException {
    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        Charset charset = HTTP.DEF_CONTENT_CHARSET;
        ContentType contentType = ContentType.get(response.getEntity());
        if(contentType != null) {
            if(contentType.getCharset() != null) {
                charset = contentType.getCharset();
            }
        }
        try {
            final JsonObject json = JsonParser.parseReader(new InputStreamReader(response.getEntity().getContent(), charset)).getAsJsonObject();
            final String token = json.getAsJsonPrimitive("token").getAsString();
            final String endpoint = json.getAsJsonPrimitive("endpoint").getAsString();
            return new AuthenticationResponse(response, token,
                    Collections.singleton(new Region(null, URI.create(endpoint), null, true)));
        }
        catch(JsonParseException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
            || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new AuthorizationException(new Response(response));
    }
    throw new GenericException(new Response(response));
}
 
Example 10
Source File: ResponseCapturingWrapper.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
public void setContentType(String type) {
    ContentType parsedContentType = ContentType.parse(type);
    this.contentType = parsedContentType.getMimeType();
    if (parsedContentType.getCharset() != null) {
        this.characterEncoding = parsedContentType.getCharset().name();
    }
    updateContentTypeHeader();
}
 
Example 11
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private String getBody(HttpResponse response) throws Exception {
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader(HTTP_HEADER_CONTENT_TYPE).getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 12
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String handleMultipartResponse(String mimeType, InputStream inputStream, IPipeLineSession session, HttpResponseHandler httpHandler) throws IOException, SenderException {
	String result = null;
	try {
		InputStreamDataSource dataSource = new InputStreamDataSource(mimeType, inputStream);
		MimeMultipart mimeMultipart = new MimeMultipart(dataSource);
		for (int i = 0; i < mimeMultipart.getCount(); i++) {
			BodyPart bodyPart = mimeMultipart.getBodyPart(i);
			boolean lastPart = mimeMultipart.getCount() == i + 1;
			if (i == 0) {
				String charset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
				ContentType contentType = ContentType.parse(bodyPart.getContentType());
				if(contentType.getCharset() != null)
					charset = contentType.getCharset().name();

				InputStream bodyPartInputStream = bodyPart.getInputStream();
				result = Misc.streamToString(bodyPartInputStream, charset);
				if (lastPart) {
					bodyPartInputStream.close();
				}
			} else {
				// When the last stream is read the
				// httpMethod.releaseConnection() can be called, hence pass
				// httpMethod to ReleaseConnectionAfterReadInputStream.
				session.put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpHandler : null, bodyPart.getInputStream()));
			}
		}
	} catch(MessagingException e) {
		throw new SenderException("Could not read mime multipart response", e);
	}
	return result;
}
 
Example 13
Source File: HttpService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static String contentAsString(URI uri, Credentials auth, ProgressMonitor<Long> monitor) throws IOException {
   CloseableHttpResponse rsp = get(uri,auth);
   try {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();
      ContentType ct = ContentType.get(entity);

      Charset cs = ct.getCharset();
      if (cs == null) cs = StandardCharsets.UTF_8;

      long length = entity.getContentLength();
      int clength = (int)length;
      if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;

      try (InputStream is = entity.getContent();
           ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
         copy(is, os, length, monitor);
         EntityUtils.consume(entity);
         return new String(os.toByteArray(), cs);
      }
   } finally {
      rsp.close();
   }
}
 
Example 14
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private String getBody(HttpResponse response) throws Exception {
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 15
Source File: HttpConnHelper.java    From QiQuYingServer with Apache License 2.0 5 votes vote down vote up
/**
 * 创建响应处理器ResponseHandler
 * 
 * @return
 */
public static <T> ResponseHandler<T> prepareResponseHandler(final Class<T> c) {
	ResponseHandler<T> rh = new ResponseHandler<T>() {
		@Override
		public T handleResponse(final HttpResponse response)
				throws IOException {

			StatusLine statusLine = response.getStatusLine();
			HttpEntity entity = response.getEntity();
			if (statusLine.getStatusCode() >= 300) {
				throw new HttpResponseException(statusLine.getStatusCode(),
						statusLine.getReasonPhrase());
			}
			if (entity == null) {
				throw new ClientProtocolException(
						"Response contains no content");
			}
			ContentType contentType = ContentType.getOrDefault(entity);
			Charset charset = contentType.getCharset();
			Reader reader = new InputStreamReader(entity.getContent(),
					charset);
			long hand_start = System.currentTimeMillis();
			T t = gson.fromJson(reader, c);
			long hand_end = System.currentTimeMillis();
			double cost = (hand_end-hand_start)/1000.0;
			log.info("handleResponse convert cost time "+cost+"s");
			return t;
		}
	};
	return rh;
}
 
Example 16
Source File: HTTPUtil.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 使用.p12商户证书文件发送HTTP_POST请求
 * @see 1)该方法允许自定义任何格式和内容的HTTP请求报文体
 * @see 2)该方法会自动关闭连接,释放资源
 * @see 3)方法内设置了连接和读取超时(时间由本工具类全局变量限定),超时或发生其它异常将抛出RuntimeException
 * @see 4)请求参数含中文等特殊字符时,可直接传入本方法,方法内部会使用本工具类设置的全局SeedConstants.DEFAULT_CHARSET对其转码
 * @see 5)该方法在解码响应报文时所采用的编码,取自响应消息头中的[Content-Type:text/html; charset=GBK]的charset值
 * @see   若响应头中无Content-Type或charset属性,则会使用SeedConstants.DEFAULT_CHARSET作为响应报文的解码字符集,否则以charset的值为准
 * @param reqURL      请求地址
 * @param reqData     请求报文,无参数时传null即可,多个参数则应拼接为param11=value11&22=value22&33=value33的形式
 * @param contentType 设置请求头的contentType,传空则默认使用application/x-www-form-urlencoded; charset=UTF-8
 * @param filepath    证书文件路径(含文件名),比如:/app/p12/apiclient_cert.p12
 * @param password    证书密码
 * @return 远程主机响应正文
 */
public static String postWithP12(String reqURL, String reqData, String contentType, String filepath, String password){
    LogUtil.getLogger().info("请求{}的报文为-->>[{}]", reqURL, reqData);
    String respData = "";
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SO_TIMEOUT);
    HttpPost httpPost = new HttpPost(reqURL);
    //由于下面使用的是new StringEntity(....),所以默认发出去的请求报文头中CONTENT_TYPE值为text/plain; charset=ISO-8859-1
    //这就有可能会导致服务端接收不到POST过去的参数,比如运行在Tomcat6.0.36中的Servlet,所以我们手工指定CONTENT_TYPE头消息
    if(StringUtils.isBlank(contentType)){
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=" + SeedConstants.DEFAULT_CHARSET);
    }else{
        httpPost.setHeader(HTTP.CONTENT_TYPE, contentType);
    }
    httpPost.setEntity(new StringEntity(null==reqData?"":reqData, SeedConstants.DEFAULT_CHARSET));
    try{
        httpClient = addTLSSupport(httpClient, filepath, password);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if(null != entity){
            String decodeCharset;
            ContentType respContentType = ContentType.get(entity);
            if(null == respContentType){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else if(null == respContentType.getCharset()){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else{
                decodeCharset = respContentType.getCharset().displayName();
            }
            respData = EntityUtils.toString(entity, decodeCharset);
        }
        LogUtil.getLogger().info("请求{}得到应答<<--[{}]", reqURL, respData);
        return respData;
    }catch(ConnectTimeoutException cte){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时连接超时", cte);
    }catch(SocketTimeoutException ste){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时读取超时", ste);
    }catch(Exception e){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时遇到异常", e);
    }finally{
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 17
Source File: HTTPUtil.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 发送HTTP_POST请求
 * @see 1)该方法允许自定义任何格式和内容的HTTP请求报文体
 * @see 2)该方法会自动关闭连接,释放资源
 * @see 3)方法内设置了连接和读取超时(时间由本工具类全局变量限定),超时或发生其它异常将抛出RuntimeException
 * @see 4)请求参数含中文等特殊字符时,可直接传入本方法,方法内部会使用本工具类设置的全局SeedConstants.DEFAULT_CHARSET对其转码
 * @see 5)该方法在解码响应报文时所采用的编码,取自响应消息头中的[Content-Type:text/html; charset=GBK]的charset值
 * @see   若响应头中无Content-Type或charset属性,则会使用SeedConstants.DEFAULT_CHARSET作为响应报文的解码字符集,否则以charset的值为准
 * @param reqURL      请求地址
 * @param reqData     请求报文,无参数时传null即可,多个参数则应拼接为param11=value11&22=value22&33=value33的形式
 * @param contentType 设置请求头的contentType,传空则默认使用application/x-www-form-urlencoded; charset=UTF-8
 * @return 远程主机响应正文
 */
public static String post(String reqURL, String reqData, String contentType){
    LogUtil.getLogger().info("请求{}的报文为-->>[{}]", reqURL, reqData);
    String respData = "";
    HttpClient httpClient = new DefaultHttpClient();
    //-------------------------------------------------------------------
    //http://jinnianshilongnian.iteye.com/blog/2089792
    //https://my.oschina.net/ramboo/blog/519871
    //http://www.cnblogs.com/likaitai/p/5431246.html
    //HttpParams params = new BasicHttpParams();
    ////设置连接超时=2s
    //params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2*1000);
    ////设置读取超时=10s
    //params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10*1000);
    ////设置连接不够用时的等待超时时间=500ms
    //params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 500L);
    ////提交请求前测试连接是否可用
    //params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
    //PoolingClientConnectionManager poolingManager = new PoolingClientConnectionManager();
    ////设置整个连接池的最大连接数(假设只连接一个主机)
    ////MaxtTotal是整个池子的大小,DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分
    ////比如MaxtTotal=400,DefaultMaxPerRoute=200,当只连接到https://jadyer.cn/时,到该主机的并发最多只有200,而非400
    ////而当连接https://jadyer.cn/和http://blog.csdn.net/jadyer时,到每个主机的并发最多只有200,即加起来是400(但不能超过400)
    //poolingManager.setMaxTotal(200);
    //poolingManager.setDefaultMaxPerRoute(poolingManager.getMaxTotal());
    ////另外设置http client的重试次数,默认是3次;当前是禁用掉(如果项目量不到,这个默认即可)
    ////httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    //-------------------------------------------------------------------
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SO_TIMEOUT);
    HttpPost httpPost = new HttpPost(reqURL);
    //由于下面使用的是new StringEntity(....),所以默认发出去的请求报文头中CONTENT_TYPE值为text/plain; charset=ISO-8859-1
    //这就有可能会导致服务端接收不到POST过去的参数,比如运行在Tomcat6.0.36中的Servlet,所以我们手工指定CONTENT_TYPE头消息
    if(StringUtils.isBlank(contentType)){
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=" + SeedConstants.DEFAULT_CHARSET);
    }else{
        httpPost.setHeader(HTTP.CONTENT_TYPE, contentType);
    }
    httpPost.setEntity(new StringEntity(null==reqData?"":reqData, SeedConstants.DEFAULT_CHARSET));
    try{
        httpClient = addTLSSupport(httpClient);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if(null != entity){
            String decodeCharset;
            ContentType respContentType = ContentType.get(entity);
            if(null == respContentType){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else if(null == respContentType.getCharset()){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else{
                decodeCharset = respContentType.getCharset().displayName();
            }
            respData = EntityUtils.toString(entity, decodeCharset);
        }
        LogUtil.getLogger().info("请求{}得到应答<<--[{}]", reqURL, respData);
        return respData;
    }catch(ConnectTimeoutException cte){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时连接超时", cte);
    }catch(SocketTimeoutException ste){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时读取超时", ste);
    }catch(Exception e){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时遇到异常", e);
    }finally{
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 18
Source File: HTTPUtil.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 发送HTTPS_POST请求
 * @see 1)该方法亦可处理HTTP_POST请求
 * @see 2)该方法会自动关闭连接,释放资源
 * @see 3)方法内自动注册443作为HTTPS端口,即处理HTTPS请求时,默认请求对方443端口
 * @see 4)方法内设置了连接和读取超时(时间由本工具类全局变量限定),超时或发生其它异常将抛出RuntimeException
 * @see 5)请求参数含中文等特殊字符时,可直接传入本方法,方法内部会使用本工具类设置的全局SeedConstants.DEFAULT_CHARSET对其转码
 * @see 6)该方法在解码响应报文时所采用的编码,取自响应消息头中的[Content-Type:text/html; charset=GBK]的charset值
 * @see   若响应头中无Content-Type或charset属性,则会使用SeedConstants.DEFAULT_CHARSET作为响应报文的解码字符集,否则以charset的值为准
 * @param reqURL   请求地址
 * @param paramMap 请求参数,无参数时传null即可
 * @return 远程主机响应正文
 */
public static String post(String reqURL, Map<String, String> paramMap){
    LogUtil.getLogger().info("请求{}的报文为-->>{}", reqURL, JadyerUtil.buildStringFromMap(paramMap));
    String respData = "";
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SO_TIMEOUT);
    try {
        HttpPost httpPost = new HttpPost(reqURL);
        // 由于下面使用的是new UrlEncodedFormEntity(....),所以这里不需要手工指定CONTENT_TYPE为application/x-www-form-urlencoded
        // 因为在查看了HttpClient的源码后发现,UrlEncodedFormEntity所采用的默认CONTENT_TYPE就是application/x-www-form-urlencoded
        // httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=" + encodeCharset);
        if (MapUtils.isNotEmpty(paramMap)) {
            List<NameValuePair> formParamList = new ArrayList<>();
            // for(Map.Entry<String,String> entry : paramMap.entrySet()){
            //    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            // }
            // JDK8开始推荐这么迭代
            paramMap.forEach((key, value) -> {
                formParamList.add(new BasicNameValuePair(key, value));
            });
            httpPost.setEntity(new UrlEncodedFormEntity(formParamList, SeedConstants.DEFAULT_CHARSET));
        }
        httpClient = addTLSSupport(httpClient);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if(null != entity){
            String decodeCharset;
            ContentType respContentType = ContentType.get(entity);
            if(null == respContentType){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else if(null == respContentType.getCharset()){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else{
                decodeCharset = respContentType.getCharset().displayName();
            }
            respData = EntityUtils.toString(entity, decodeCharset);
        }
        LogUtil.getLogger().info("请求{}得到应答<<--[{}]", reqURL, respData);
        return respData;
    }catch(ConnectTimeoutException cte){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时连接超时", cte);
    }catch(SocketTimeoutException ste){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时读取超时", ste);
    }catch(Exception e){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时遇到异常", e);
    }finally{
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 19
Source File: HTTPUtil.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 发送上传文件的HTTP_POST请求
 * @see 1)该方法用来上传文件
 * @see 2)该方法会自动关闭连接,释放资源
 * @see 3)方法内设置了连接和读取超时(时间由本工具类全局变量限定),超时或发生其它异常将抛出RuntimeException
 * @see 4)请求参数含中文等特殊字符时,可直接传入本方法,方法内部会使用本工具类设置的全局SeedConstants.DEFAULT_CHARSET对其转码
 * @see 5)该方法在解码响应报文时所采用的编码,取自响应消息头中的[Content-Type:text/html; charset=GBK]的charset值
 * @see   若响应头中无Content-Type或charset属性,则会使用SeedConstants.DEFAULT_CHARSET作为响应报文的解码字符集,否则以charset的值为准
 * @param reqURL       请求地址
 * @param filename     待上传的文件名
 * @param is           待上传的文件流
 * @param fileBodyName 远程主机接收文件域的名字,相当于前台表单中的文件域名称<input type="file" name="fileBodyName">
 * @param params       请求参数,无参数时传null即可
 * @return 远程主机响应正文
 */
public static String upload(String reqURL, String filename, InputStream is, String fileBodyName, Map<String, String> params){
    LogUtil.getLogger().info("请求{}的报文为-->>{}", reqURL, JadyerUtil.buildStringFromMap(params));
    String respData = "";
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SO_TIMEOUT);
    HttpPost httpPost = new HttpPost(reqURL);
    //Charset用来保证文件域中文名不乱码,非文件域中文不乱码的话还要像下面StringBody中再设置一次Charset
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(SeedConstants.DEFAULT_CHARSET));
    File tmpFile = new File(filename);
    try{
        FileUtils.copyInputStreamToFile(is, tmpFile);
        reqEntity.addPart(fileBodyName, new FileBody(tmpFile));
        if(null != params){
            for(Map.Entry<String,String> entry : params.entrySet()){
                reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName(SeedConstants.DEFAULT_CHARSET)));
            }
        }
        httpPost.setEntity(reqEntity);
        httpClient = addTLSSupport(httpClient);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if(null != entity){
            String decodeCharset;
            ContentType respContentType = ContentType.get(entity);
            if(null == respContentType){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else if(null == respContentType.getCharset()){
                decodeCharset = SeedConstants.DEFAULT_CHARSET;
            }else{
                decodeCharset = respContentType.getCharset().displayName();
            }
            respData = EntityUtils.toString(entity, decodeCharset);
        }
        LogUtil.getLogger().info("请求{}得到应答<<--[{}]", reqURL, respData);
        return respData;
    }catch(ConnectTimeoutException cte){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时连接超时", cte);
    }catch(SocketTimeoutException ste){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时读取超时", ste);
    }catch(Exception e){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时遇到异常", e);
    }finally{
        httpClient.getConnectionManager().shutdown();
        //File file = new File("e:\\xuanyu\\test\\jadyer.png");
        //file.getCanonicalPath() = E:\xuanyu\test\jadyer.png
        //file.getAbsolutePath()  = e:\xuanyu\test\jadyer.png
        //file.getPath()          = e:\xuanyu\test\jadyer.png
        //file.getParent()        = e:\xuanyu\test
        //file.getName()          = jadyer.png
        LogUtil.getLogger().info("临时文件[{}]删除[{}]", tmpFile.getAbsolutePath(), tmpFile.delete()?"成功":"失败");
    }
}
 
Example 20
Source File: AbstractUriExplorer.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
static String getCharset(HttpResponse response) {
  ContentType contentType = ContentType.getOrDefault(response.getEntity());
  Charset charset = contentType.getCharset();
  return charset == null ? "UTF-8" : charset.name();
}