在开始之前,我们需要先引入 maven 依赖。如下:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.2</version> </dependency>
注意:提交表单的 MultipartEntityBuilder 类需要引入 httpmime 库。
实例1:提交一个JSON数据到后端,即我们常说的 Restful 接口。代码如下:
package com.huangx.httpcomponents; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * 使用 http components 发起 POST 请求 * @author huangxin 2019/12/2 */ public class PostDemo { public static void main(String[] args) throws Exception { // (1) 创建HttpGet实例 HttpPost post = new HttpPost("https://127.0.0.1:8080/env/postEnvObj"); // (2) 设置请求体 Map<String,Object> data = new HashMap<>(); data.put("name", "admin"); data.put("email", "admin@163.com"); StringEntity myEntity = new StringEntity(JSONObject.toJSONString(data), ContentType.APPLICATION_JSON); post.setEntity(myEntity); // (3) 使用HttpClient发送get请求,获得返回结果HttpResponse HttpClient http = new DefaultHttpClient(); HttpResponse response = http.execute(post); // (4) 读取返回结果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("statusCode=" + statusCode); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } }
服务端代码如下:
/** * 使用 JSON 格式提交数据到服务端 * @param userEntity 用户数据 * @return */ @RequestMapping(value = "/postEnvObj", method = RequestMethod.POST) @ResponseBody public String postEnvObj(@RequestBody UserEntity userEntity) { LOG.info("#### /postEnvObj userEntity={}", JSONObject.toJSONString(userEntity)); Map<String,Object> retData = new HashMap<>(); retData.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())); retData.put("content", userEntity); return JSONObject.toJSONString(retData, true); }
注意:服务端我采用Spring Boot进行实现。
实例2:使用 POST 方式提交一个表单到后端服务器。代码如下:
package com.huangx.httpcomponents; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; 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.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /** * 使用 http components 发起 POST 请求,提交表单数据 * @author huangxin 2019/12/2 */ public class PostDemo2 { public static void main(String[] args) throws Exception { // (1) 创建HttpGet实例 HttpPost post = new HttpPost("https://127.0.0.1:8080/env/postEnv"); // (2) 设置请求体 // 提交表单数据 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("name", new StringBody("admin", ContentType.create("text/plain", Consts.UTF_8))); builder.addPart("email", new StringBody("admin@163.com", ContentType.create("text/plain", Consts.UTF_8))); HttpEntity reqEntity = builder.build(); post.setEntity(reqEntity); // (3) 使用HttpClient发送get请求,获得返回结果HttpResponse HttpClient http = new DefaultHttpClient(); HttpResponse response = http.execute(post); // (4) 读取返回结果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("statusCode=" + statusCode); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } }
服务端代码如下:
/** * 提交表单数据到服务端,然后将数据返回 * @param name 名称 * @param email 邮箱 * @return */ @RequestMapping(value = "/postEnv", method = RequestMethod.POST) @ResponseBody public String postEnv(String name, String email) { LOG.info("#### /postEnv name={}, email={}", name, email); Map<String,Object> retData = new HashMap<>(); retData.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())); Map<String,Object> content = new HashMap<>(); content.put("name", name); content.put("email", email); retData.put("content", content); return JSONObject.toJSONString(retData, true); }