关于Java去连接HTTP地址的操作

jopen 9年前

使用HTTPClient进行操作,可以忽略SSL

/**   * @author Kai   * @Date 2015-7-28 19:47:16   */  public class HTTPClient {        //HTTP请求读取超时时间      private static final int SOCKET_TIME_OUT = 5000;      //HTTP请求连接时间      private static final int CONNECT_TIME_OUT = 5000;      //请求重试次数      private static final int RETRY_TIMES = 3;             /**       *        * @param address 请求地址       * @param method  请求方式       * @param params 请求参数       * @param paramSendType 发送类型       * @param cookies 设置cookies值发送       * @return        */      public String request(String address, String method, String params, String paramSendType, String cookies) {          address = address.trim();          CloseableHttpResponse closeableHttpResponse = null;          if (SupportProtocol.HTTP_METHOD_GET.equalsIgnoreCase(method)) {              closeableHttpResponse = this.GET(address, params, paramSendType, cookies);          } else if (SupportProtocol.HTTP_METHOD_POST.equalsIgnoreCase(method)) {              closeableHttpResponse = this.POST(address, params, paramSendType, cookies);          } else if (SupportProtocol.HTTP_METHOD_PUT.equalsIgnoreCase(method)) {              closeableHttpResponse = this.PUT(address, params, paramSendType, cookies);          } else {              closeableHttpResponse = this.POST(address, params, paramSendType, cookies);          }            return this.buildReponseMsg(closeableHttpResponse);      }            private CloseableHttpResponse PUT(String address, String params, String paramSendType, String cookies) {          try {              URI uri = URI.create(address);              HttpPut httpPut = new HttpPut(uri);              RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();              httpPut.setConfig(requestConfig);                if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {                  httpPut.setHeader("Content-Type", "application/json; charset=UTF-8");                  StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);                  httpPut.setEntity(entity);              } else if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {                  httpPut.setHeader("Content-Type", "application/xml; charset=UTF-8");                  StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);                  httpPut.setEntity(entity);              } else {                  httpPut.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");                  StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);                  httpPut.setEntity(entity);              }                if (StrUtil.isNotEmpty(cookies)) {                  httpPut.setHeader("Cookie", cookies);              }                CloseableHttpClient httpClient = HttpClients.createDefault();                if (address.toLowerCase().startsWith("https")) {                  httpClient = this.createSSLClientDefault();              }                return httpClient.execute(httpPut);          } catch (Exception ex) {              LogUtil.error(ex);          }          return null;      }        private CloseableHttpResponse GET(String address, String params, String paramSendType, String cookies) {          try {              URI uri;              if (EmptyUtil.isNotEmpty(params)) {                  uri = URI.create(String.format("%s?%s", address, params));              } else {                  uri = URI.create(address);              }                HttpGet httpGet = new HttpGet(uri);              RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();              httpGet.setConfig(requestConfig);                if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {                  httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");              } else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {                  httpGet.setHeader("Content-Type", "application/xml; charset=UTF-8");              } else {                  httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");              }                if (StrUtil.isNotEmpty(cookies)) {                  httpGet.setHeader("Cookie", cookies);              }              CloseableHttpClient httpClient = HttpClients.createDefault();              if (address.toLowerCase().startsWith("https")) {                  httpClient = this.createSSLClientDefault();              }              return httpClient.execute(httpGet);          } catch (Exception ex) {              LogUtil.error(ex);          }          return null;      }        private CloseableHttpResponse POST(String address, String params, String paramSendType, String cookies) {          try {              URI uri = URI.create(address);              HttpPost httpPost = new HttpPost(uri);              RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();              httpPost.setConfig(requestConfig);                if (SupportProtocol.SUPPORT_JSON.equalsIgnoreCase(paramSendType)) {                  httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");                  StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);                  httpPost.setEntity(entity);              } else if (SupportProtocol.SUPPORT_XML.equalsIgnoreCase(paramSendType)) {                  httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");                  StringEntity entity = new StringEntity(params, ContentType.APPLICATION_XML);                  httpPost.setEntity(entity);              } else {                  httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");                  StringEntity entity = new StringEntity(params, ContentType.APPLICATION_FORM_URLENCODED);                  httpPost.setEntity(entity);              }                if (StrUtil.isNotEmpty(cookies)) {                  httpPost.setHeader("Cookie", cookies);              }                CloseableHttpClient httpClient = HttpClients.createDefault();              if (address.toLowerCase().startsWith("https")) {                  httpClient = this.createSSLClientDefault();              }              return httpClient.execute(httpPost);          } catch (Exception ex) {              LogUtil.error(ex);          }          return null;      }        private CloseableHttpClient createSSLClientDefault() {          try {              SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {                  @Override                  public boolean isTrusted(X509Certificate[] chain,                          String authType) throws CertificateException {                      return true;                  }              }).build();              SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);              return HttpClients.custom().setSSLSocketFactory(ssf).build();          } catch (Exception e) {              LogUtil.error(e.getMessage());          }          return HttpClients.createDefault();      }        private String buildReponseMsg(CloseableHttpResponse closeableHttpResponse) {          if (closeableHttpResponse == null) {              return null;          }          try {              int code = closeableHttpResponse.getStatusLine().getStatusCode();              String msg = EntityUtils.toString(closeableHttpResponse.getEntity());              if (code == HttpStatus.SC_OK) {                  return msg;              }          } catch (Exception ex) {              LogUtil.error(ex);          }          return null;      }  }


使用URLConnection读取数据,访问HTTPS貌似有问题

package com.k.ctc.http;    import java.io.BufferedReader;  import java.io.InputStreamReader;  import java.io.OutputStreamWriter;  import java.io.UnsupportedEncodingException;  import java.net.URL;  import java.net.URLConnection;  import java.net.URLEncoder;  import java.util.Map;    /**   *   * @author Kai   */  public class Connector {        public String GET(String address, Map<String, String> params) throws Exception {          String param = this.buildParams(params);          URL url = new URL(address + "?" + param);          URLConnection conn = url.openConnection();          return this.readData(conn);      }        public String GET(String address, String params) throws Exception {          URL url = new URL(address + "?" + params);          URLConnection conn = url.openConnection();          return this.readData(conn);      }        public String POST(String address, Map<String, String> params) throws Exception {          String param = this.buildParams(params);          URL url = new URL(address);          URLConnection conn = url.openConnection();          this.postData(conn, param);          return this.readData(conn);      }        public String POST(String address, String param) throws Exception {          URL url = new URL(address);          URLConnection conn = url.openConnection();          this.postData(conn, param);          return this.readData(conn);      }        private String buildParams(Map<String, String> params) throws UnsupportedEncodingException {          StringBuilder sb = new StringBuilder();          for (Map.Entry<String, String> param : params.entrySet()) {              sb.append(param.getKey()).append("=");              sb.append(URLEncoder.encode(param.getValue(), "UTF-8"));              sb.append("&");          }          return sb.toString();      }        private void postData(final URLConnection conn, String requestData) throws Exception {          conn.setDoOutput(true);          OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());          wr.write(requestData);          wr.flush();          wr.close();      }        private String readData(final URLConnection conn) throws Exception {          String responseData = "";          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));          String line;          while ((line = rd.readLine()) != null) {              responseData += line;          }          responseData = new String(responseData.getBytes(), "UTF-8");          rd.close();          return responseData;      }  }


做个代码记录 Maven引用

<dependency>      <groupId>org.apache.httpcomponents</groupId>      <artifactId>httpclient</artifactId>      <version>4.4</version>  </dependency>  <dependency>      <groupId>org.apache.httpcomponents</groupId>      <artifactId>httpcore</artifactId>      <version>4.4</version>  </dependency>  <dependency>      <groupId>org.apache.httpcomponents</groupId>      <artifactId>httpcore-nio</artifactId>      <version>4.4</version>  </dependency>



来自: http://my.oschina.net/Kxvz/blog/599039