大家好,又见面了,我是你们的朋友全栈君。
使用HttpClient发送请求的一般步骤
(1) 创建HttpClient对象。
(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3) 如果需要发送请求参数,可调用HttpGet同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
(4) 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5) 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
(6) 释放连接。无论执行方法是否成功,都必须释放连接
下面分别介绍使用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();
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/127056.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...