Exemplo n.º 1
0
  public static HttpResponse execute(HttpRequest httpRequest) throws IOException {
    HttpConfig httpConfig =
        httpRequest.getHttpConfig() == null ? HttpConfig.DEFAULT : httpRequest.getHttpConfig();

    HttpURLConnection connection = null;
    try {
      connection = getHttpURLConnection(httpRequest.getUrl(), httpConfig); // 获取连接
      setTimeOut(httpConfig, connection); // 设置超时
      connection.setInstanceFollowRedirects(httpConfig.isRedirectEnable()); // 设置重定向
      connection.setUseCaches(false); // 不使用缓存
      connection.setDoInput(true); // 可输入输出
      if (httpRequest instanceof HttpRequest) { // 设置METHOD
        connection.setRequestMethod(httpRequest.getMethodName());
        connection.setDoOutput(true);
      }
      if (null != httpRequest.getHeaders()) { // 设置headers
        for (Map.Entry<String, String> entryTmp : httpRequest.getHeaders().entrySet()) {
          connection.setRequestProperty(entryTmp.getKey(), entryTmp.getValue());
        }
      }
      return getHttpResponse(connection, httpRequest);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
Exemplo n.º 2
0
 private static void setTimeOut(HttpConfig httpConfig, HttpURLConnection conn) {
   if (httpConfig.getConnectTimeout() > 0) {
     conn.setConnectTimeout(httpConfig.getConnectTimeout());
   }
   if (httpConfig.getRequestTimeout() > 0) {
     conn.setReadTimeout(httpConfig.getRequestTimeout());
   }
 }
Exemplo n.º 3
0
 private static HttpURLConnection getHttpURLConnection(URL url, HttpConfig httpConfig)
     throws IOException {
   if (httpConfig.getHttpProxy() == null) {
     return (HttpURLConnection) (url).openConnection();
   } else {
     Proxy proxy =
         new Proxy(
             Proxy.Type.HTTP,
             new InetSocketAddress(
                 httpConfig.getHttpProxy().getHost(), httpConfig.getHttpProxy().getPort()));
     return (HttpURLConnection) (url).openConnection(proxy);
   }
 }