mark java發起http請求的方式

炸雞店老闆發表於2018-01-03

系統間的互動,除了webservice,最簡單應該就是http方式。
比如微信平臺、支付寶、微博、QQ的api呼叫。
常用的方式及example:

  • JDK 提供的機制
/**
 * 最簡單的使用,參考:https://developer.android.com/reference/java/net/HttpURLConnection.html
 */
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} finally {
    urlConnection.disconnect();
}
/**
 * 帶cookie 的post請求
 * cookie設定是系統級別的,jvm通用
 **/
public static void main(String[] args) throws IOException, URISyntaxException {
    CookieManager cookieManager = new CookieManager();
    CookieHandler.setDefault(cookieManager);

    HttpCookie cookie = new HttpCookie("sso.dd.com", "b1846e53e99c7");
    cookie.setDomain(".dd.com");
    cookie.setPath("/");
    cookieManager.getCookieStore().add(new URI("http://erp.dd.com/"), cookie);

    URL url = new URL("http://erp.dd.com/portal/clock/clockInfo");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(1000);
    connection.setConnectTimeout(1000);
    connection.setRequestMethod("POST");
    try {
        InputStream in = new BufferedInputStream(connection.getInputStream());
        readStream(in);
    } finally {
        connection.disconnect();
    }
}
/**
 * spring-web的封裝
 * 參考:org.springframework.http.client.SimpleClientHttpRequestFactory
 * 參考:org.springframework.web.client.RestTemplate
 */
  • httpcomponents-client
/**
 * 重試機制,比如重試次數、根據Exception型別、或者動態調整重試請求
 **/
public static HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

       public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
           System.out.println(exception.getMessage());
           if (executionCount <= 5) {
               // Do not retry if over max retry count
               return true;
           }
           return false;
       }
};

/**
 * 使用httpcomponents-client 傳送get請求
 **/
public static void main(String[] args) throws IOException {
      // CloseableHttpClient httpClient = HttpClients.createDefault();
      CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(myRetryHandler).build();
      RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build();
      HttpGet httpget = new HttpGet("http://api.github.com/users/PivotalSoftware");
      httpget.setConfig(requestConfig);
      CloseableHttpResponse response = httpClient.execute(httpget);
      try {
          HttpEntity entity = response.getEntity();
          if (entity != null) {
              InputStream instream = entity.getContent();
              try {
                  readStream(instream);
              } finally {
                  instream.close();
              }
          }
      } finally {
          response.close();
      }
}

參考: 基礎使用方式

  • okhttp

    // TODO

相關文章