程序之中模拟表单发起GET,POST请求以及实现文件上传
程序员文章站
2022-07-13 13:54:32
...
一、在程序中经常会碰到要模拟表单发送请求的情况,此时可以使用JDK自带的UrlConnection,不过它不够灵活。一般HttpClient用的更普遍,HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,所以要熟练掌握HttpClient的用法。
二、HttpClient的使用分为以下几步:
首先导入相应的依赖,如果是maven管理的项目,直接在pom.xml文件中放入以下配置即可(如果有冲突,自己调整jar包版本):
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<!--没有该依赖包时会报错-->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
如果不是maven管理的项目,自己到https://mvnrepository.com/下载好所需的jar包(或者下载附件中的jar包)然后放入自己的项目中即可
使用步骤:
A.创建HttpClient对象
B.创建请求方法的实例,并指定请求URL
C.如果请求的接口需要有请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数;对于HttpGet请求也可以直接将请求参数拼接在url的后面
D.调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse
E.通过HttpResponse的getEntity()方法可获取HttpEntity对象,该对象中包含有服务器的响应内容,随后通过对该对象的处理获取需要的信息
F.不论请求成功与否都要关闭连接
三、示例代码(导入jar包,换成可用的url可以直接使用):
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class TestHttpClient {
public static void main(String[] args) throws Exception{
get();
// post();
// upload();
}
// 发送GET请求
public static void get() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://localhost:8080/test/getUserInfo?uid=6007"); //此处是将请求参数拼接在url的后面
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("***out****"+EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(response!=null){
response.close();
}
if(httpClient!=null){
response.close();
}
}
}
// 发送POST请求
public static void post() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/admin/getUserInfo");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("uid","6007")); //设置表单参数,第一个为参数的名字,第二个为参数的内容,只能为字符串
params.add(new BasicNameValuePair("name","SMITH"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params);
post.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("***out****"+EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(response!=null){
response.close();
}
if(httpClient!=null){
httpClient.close();
}
}
}
// 上传文件
public static void upload() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/app/uploadImage");
FileBody fileBody = new FileBody(new File("E:"+File.separator+"2"+File.separator+"2.jpg"));
StringBody uid = new StringBody("6007", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("img",fileBody).addPart("uid", uid).build();
//此处掉的img和uid分别为这两个参数的名称,要与请求接口中的参数的名字一样
post.setEntity(reqEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("***out****"+EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(response!=null){
response.close();
}
if(httpClient!=null){
response.close();
}
}
}
}
二、HttpClient的使用分为以下几步:
首先导入相应的依赖,如果是maven管理的项目,直接在pom.xml文件中放入以下配置即可(如果有冲突,自己调整jar包版本):
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<!--没有该依赖包时会报错-->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
如果不是maven管理的项目,自己到https://mvnrepository.com/下载好所需的jar包(或者下载附件中的jar包)然后放入自己的项目中即可
使用步骤:
A.创建HttpClient对象
B.创建请求方法的实例,并指定请求URL
C.如果请求的接口需要有请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数;对于HttpGet请求也可以直接将请求参数拼接在url的后面
D.调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse
E.通过HttpResponse的getEntity()方法可获取HttpEntity对象,该对象中包含有服务器的响应内容,随后通过对该对象的处理获取需要的信息
F.不论请求成功与否都要关闭连接
三、示例代码(导入jar包,换成可用的url可以直接使用):
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class TestHttpClient {
public static void main(String[] args) throws Exception{
get();
// post();
// upload();
}
// 发送GET请求
public static void get() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://localhost:8080/test/getUserInfo?uid=6007"); //此处是将请求参数拼接在url的后面
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("***out****"+EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(response!=null){
response.close();
}
if(httpClient!=null){
response.close();
}
}
}
// 发送POST请求
public static void post() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/admin/getUserInfo");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("uid","6007")); //设置表单参数,第一个为参数的名字,第二个为参数的内容,只能为字符串
params.add(new BasicNameValuePair("name","SMITH"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params);
post.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("***out****"+EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(response!=null){
response.close();
}
if(httpClient!=null){
httpClient.close();
}
}
}
// 上传文件
public static void upload() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/app/uploadImage");
FileBody fileBody = new FileBody(new File("E:"+File.separator+"2"+File.separator+"2.jpg"));
StringBody uid = new StringBody("6007", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("img",fileBody).addPart("uid", uid).build();
//此处掉的img和uid分别为这两个参数的名称,要与请求接口中的参数的名字一样
post.setEntity(reqEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null){
System.out.println("***out****"+EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(response!=null){
response.close();
}
if(httpClient!=null){
response.close();
}
}
}
}
上一篇: MetaQ技术内幕——源码分析(三)
下一篇: httpclient,URL