コード例 #1
0
ファイル: HttpClient.java プロジェクト: cncduLee/http-sdk
 private static HttpResponse getHttpResponse(HttpURLConnection connection, HttpRequest httpRequest)
     throws IOException {
   BufferedReader in = null; // 站在机器的角度,从远端读入内存
   // OutputStream out = null;//站在机器的角度,从内存写入远端
   try {
     httpRequest.responseBody(connection); // 写入请求参数值(对于GET不需要,)
     String charset = getCharset(connection); // 获取content type
     StringBuilder sb = new StringBuilder();
     // 读取http返回的结果
     in =
         new BufferedReader(
             new InputStreamReader(
                 connection.getInputStream(),
                 charset == null ? Constant.DEFAULT_CHARSET : charset));
     String line = null;
     while ((line = in.readLine()) != null) {
       sb.append(CTRL).append(line);
     }
     return HttpResponse.createInstance()
         .setReturnCode(connection.getResponseCode())
         .setResponseBody(sb.toString())
         .setHeaders(connection.getHeaderFields())
         .build();
   } finally {
     IOUtil.closeQuietly(in); // 关闭流 IOUtil.closeQuietly(out);
   }
 }
コード例 #2
0
ファイル: HttpClient.java プロジェクト: cncduLee/http-sdk
  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();
      }
    }
  }