Java常用开源库: apache HttpClient 4.x, oktttp, jetty HttpClient

文章目录

  • apache httpclient
    • GET
    • POST Form
    • POST String
    • 上传文件/Multipart
    • 设置超时
    • 启用cookie
  • okhttp
    • 基本用法
    • 上传文件
    • POST
    • 设置超时
    • websocket
  • jetty httpclient

apache httpclient

https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime/
http://hc.apache.org/httpcomponents-client-ga/index.html

GET

       URIBuilder builder = new URIBuilder("http://www.baidu.com/s");
       builder.addParameter("wd", "wzj_whut");
       String url = builder.toString();
       try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
   
           final HttpGet httpget = new HttpGet(url);
           httpget.addHeader(HttpHeaders.AUTHORIZATION, "token ");
           CloseableHttpResponse responseBody = httpclient.execute(httpget);
           if(responseBody.getStatusLine().getStatusCode() == 200) {
   
               String responseText = EntityUtils.toString(responseBody.getEntity());
               System.out.println(responseText);
           }
       }

POST Form

      String url = "https://ufosdk.baidu.com/?m=Client&a=postMsg";
      try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
   
          final HttpPost post = new HttpPost(url);

          List<NameValuePair> formParams = new ArrayList<NameValuePair>();
          formParams.add(new BasicNameValuePair("content", "hello"));
          UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
          post.setEntity(entity);
          //post.setEntity(new StringEntity("q=httpclient", ContentType.DEFAULT_TEXT));
          CloseableHttpResponse responseBody = httpclient.execute

你可能感兴趣的:(后端)