空夜

java发送http请求的两种方式:HTTPClient和CloseableHttpClient
下面分别介绍使用HTTPClient和CloseableHTTPClient进行Get和Post请求的方式。Htt...
扫描右侧二维码阅读全文
07
2018/11

java发送http请求的两种方式:HTTPClient和CloseableHttpClient

下面分别介绍使用HTTPClient和CloseableHTTPClient进行Get和Post请求的方式。

HttpClient

使用commons-httpclient.jar,maven依赖如下:

    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>

java示例代码如下:

package com.example.study.demo.http;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

/**
 * HttpClient使用示例
 * jar包:commons-httpclient.jar
 */
public class HttpClientTest {
  private static void doGet() {
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod("https://www.thepaper.cn/");
    int code = 0;
    try {
      code = client.executeMethod(getMethod);
      if (code == 200) {
        String res = getMethod.getResponseBodyAsString();
        System.out.println(res);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private static void doPost() {
    String praiseUrl = "https://www.thepaper.cn/www/commentPraise.msp"; // 澎湃新闻评论点赞url
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(praiseUrl);
    // 必须设置下面这个Header
    postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
    postMethod.addParameter("commentId", "18718372"); // 评论的id,抓包获得
    try {
      int code = client.executeMethod(postMethod);
      if (code == 200) {
        String res = postMethod.getResponseBodyAsString();
        System.out.println(res);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    doGet();
    System.out.println("-----------分割线------------");
    System.out.println("-----------分割线------------");
    System.out.println("-----------分割线------------");
    doPost();
  }
}

CloseableHttpClient

使用httpclient.jar,maven依赖如下:

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>

java示例代码如下:

package com.example.study.demo.http;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * CloseableHttpClient使用示例
 * jar包:httpclient.jar
 */
public class CloseableHttpClientTest {

  public static void doGet() {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet("http://www.thepaper.cn");
    try {
      // 很奇怪,使用CloseableHttpClient来请求澎湃新闻的首页,GTE请求也必须加上下面这个Header,但是使用HTTPClient则不需要
      get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
      HttpResponse response = client.execute(get);
      String res = EntityUtils.toString(response.getEntity());
      System.out.println(res);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void doPost() {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("https://www.thepaper.cn/www/commentPraise.msp");
    try {
      post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
      List<NameValuePair> params = new ArrayList<>();
      params.add(new BasicNameValuePair("commentId", "18718372"));
      post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
      HttpResponse response = client.execute(post);
      String res = EntityUtils.toString(response.getEntity());
      System.out.println(res);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  public static void main(String[] args) {
    doGet();
    System.out.println("-----------分割线------------");
    System.out.println("-----------分割线------------");
    System.out.println("-----------分割线------------");
    doPost();

  }
}
Last modification:December 6th, 2018 at 09:33 pm
If you think my article is useful to you, please feel free to appreciate

2 comments

  1. eknown

    2016ll.gif

    1. eknows
      @eknown

      测试一下回复

Leave a Comment Cancel reply