pom依赖
<!--HttpClient的依赖
-->
<dependency>
<groupId>commons
-httpclient
</groupId
>
<artifactId>commons
-httpclient
</artifactId
>
<version>3.1</version
>
</dependency
>
<!--CloseableHttpClient的依赖
-->
<dependency>
<groupId>org
.apache
.httpcomponents
</groupId
>
<artifactId>httpclient
</artifactId
>
<version>4.5.2</version
>
</dependency
>
HttpClient 的get请求方式
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();
}
}
idea运行结果:
postman调试结果:
HttpClient 的post请求方式
private static void doPost() {
String praiseUrl
= "https://www.thepaper.cn/www/commentPraise.msp";
HttpClient client
= new HttpClient();
PostMethod postMethod
= new PostMethod(praiseUrl
);
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");
try {
int code
= client
.executeMethod(postMethod
);
if (code
== 200) {
String res
= postMethod
.getResponseBodyAsString();
System
.out
.println(res
);
}
} catch (IOException e
) {
e
.printStackTrace();
}
}
idea运行结果:
post请求结果:
CloseableHttpClient的get请求方式
public static void doGet() {
CloseableHttpClient client
= HttpClientBuilder
.create().build();
HttpGet get
= new HttpGet("http://www.thepaper.cn");
try {
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();
}
}
CloseableHttpClient的post请求方式
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();
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-6084.html