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

The following examples show how to use org.apache.http.entity.ContentType#get() . 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: 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 2
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 3
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 4
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 5
Source File: Driver.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Performs rendering on an HttpResponse.
 * <p>
 * Rendering is only performed if page can be parsed.
 * 
 * @param pageUrl
 *            The remove url from which the body was retrieved.
 * @param originalRequest
 *            The request received by esigate.
 * @param response
 *            The response which will be rendered.
 * @param renderers
 *            list of renderers to apply.
 * @return The rendered response, or the original response if if was not parsed.
 * @throws HttpErrorPage
 * @throws IOException
 */
private CloseableHttpResponse performRendering(String pageUrl, DriverRequest originalRequest,
        CloseableHttpResponse response, Renderer[] renderers) throws HttpErrorPage, IOException {

    if (!contentTypeHelper.isTextContentType(response)) {
        LOG.debug("'{}' is binary on no transformation to apply: was forwarded without modification.", pageUrl);
        return response;
    }

    LOG.debug("'{}' is text : will apply renderers.", pageUrl);

    // Get response body
    String currentValue = HttpResponseUtils.toString(response, this.eventManager);

    // Perform rendering
    currentValue = performRendering(pageUrl, originalRequest, response, currentValue, renderers);

    // Generate the new response.
    HttpEntity transformedHttpEntity = new StringEntity(currentValue, ContentType.get(response.getEntity()));
    CloseableHttpResponse transformedResponse =
            BasicCloseableHttpResponse.adapt(new BasicHttpResponse(response.getStatusLine()));
    transformedResponse.setHeaders(response.getAllHeaders());
    transformedResponse.setEntity(transformedHttpEntity);
    return transformedResponse;

}
 
Example 6
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 7
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 8
Source File: HttpResponseUtils.java    From esigate with Apache License 2.0 5 votes vote down vote up
public static ContentType getContentType(CloseableHttpResponse response) {
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        return null;
    }
    return ContentType.get(entity);
}
 
Example 9
Source File: HTTPUtil.java    From seed with Apache License 2.0 4 votes vote down vote up
/**
 * 发送HTTP_GET请求
 * @see 1)该方法会自动关闭连接,释放资源
 * @see 2)方法内设置了连接和读取超时(时间由本工具类全局变量限定),超时或发生其它异常将抛出RuntimeException
 * @see 3)请求参数含中文时,经测试可直接传入中文,HttpClient会自动编码发给Server,应用时应根据实际效果决定传入前是否转码
 * @see 4)该方法会自动获取到响应消息头中[Content-Type:text/html; charset=GBK]的charset值作为响应报文的解码字符集
 * @see   若响应头中无Content-Type或charset属性,则会使用SeedConstants.DEFAULT_CHARSET作为响应报文的解码字符集,否则以charset的值为准
 * @param requestURL 请求地址(含参数)
 * @return 远程主机响应正文
 */
public static String get(String reqURL){
    String respData = "";
    HttpClient httpClient = new DefaultHttpClient();
    //设置代理服务器
    //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("10.0.0.4", 8080));
    //连接超时2s
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    //读取超时60s
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SO_TIMEOUT);
    try{
        httpClient = addTLSSupport(httpClient);
        HttpResponse response = httpClient.execute(new HttpGet(reqURL));
        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);
            //Consume response content,主要用来关闭输入流的,对于远程返回内容不是流时,不需要执行此方法(这里只是演示)
            EntityUtils.consume(entity);
        }
        System.out.println("-----------------------------------------------------------------------------");
        StringBuilder respHeaderDatas = new StringBuilder();
        for(Header header : response.getAllHeaders()){
            respHeaderDatas.append(header.toString()).append("\r\n");
        }
        String respStatusLine = response.getStatusLine().toString(); //HTTP应答状态行信息
        String respHeaderMsg = respHeaderDatas.toString().trim();    //HTTP应答报文头信息
        String respBodyMsg = respData;                               //HTTP应答报文体信息
        System.out.println("HTTP应答完整报文=[" + respStatusLine + "\r\n" + respHeaderMsg + "\r\n\r\n" + respBodyMsg + "]");
        System.out.println("-----------------------------------------------------------------------------");
        return respData;
    }catch(ConnectTimeoutException cte){
        //Should catch ConnectTimeoutException, and don`t catch org.apache.http.conn.HttpHostConnectException
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时连接超时", cte);
    }catch(SocketTimeoutException ste){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "请求通信[" + reqURL + "]时读取超时", ste);
    }catch(ClientProtocolException cpe){
        //该异常通常是协议错误导致:比如构造HttpGet对象时传入协议不对(将'http'写成'htp')or响应内容不符合HTTP协议要求等
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时协议异常", cpe);
    }catch(ParseException pe){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时解析异常", pe);
    }catch(IOException ioe){
        //该异常通常是网络原因引起的,如HTTP服务器未启动等
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时网络异常", ioe);
    }catch(Exception e){
        throw new SeedException(CodeEnum.SYSTEM_ERROR.getCode(), "请求通信[" + reqURL + "]时遇到异常", e);
    }finally{
        //关闭连接,释放资源
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 10
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 11
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 12
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 13
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()?"成功":"失败");
    }
}