Java调用Http接口(4)--HttpClient调用Http接口
2019-11-26 16:05:39来源:博客园 阅读 ()
Java调用Http接口(4)--HttpClient调用Http接口
HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。
1、服务端
参见Java调用Http接口(1)--编写服务端
2、调用
2.1、GET请求
public static void get() { try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8"); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet(requestPath); CloseableHttpResponse response = httpClient.execute(get); System.out.println("GET返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Get(requestPath).execute().returnContent().toString(); System.out.println("GET fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } }
2.2、POST请求(发送键值对数据)
public static void post() { try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("userId", "1000")); list.add(new BasicNameValuePair("userName", "李白")); post.setEntity(new UrlEncodedFormEntity(list, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyForm(Form.form().add("userId", "1000").add("userName", "李白").build(), Charset.forName("utf-8")) .execute().returnContent().toString(); System.out.println("POST fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } }
2.3、POST请求(发送JSON数据)
public static void post2() { try { String requestPath = "http://localhost:8080/webframe/demo/test/addUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); post.setHeader("Content-type", "application/json"); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; post.setEntity(new StringEntity(param, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST json返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .addHeader("Content-type", "application/json") .bodyString(param, ContentType.APPLICATION_JSON) .execute().returnContent().toString(); System.out.println("POST json fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } }
2.4、上传文件
public static void upload() { try { String requestPath = "http://localhost:8080/webframe/demo/test/upload"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); post.setEntity(new InputStreamEntity(fileInputStream)); CloseableHttpResponse response = httpClient.execute(post); System.out.println("upload返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyStream(new FileInputStream("d:/a.jpg")) .execute().returnContent().toString(); System.out.println("upload fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } }
2.5、上传文件及发送键值对数据
public static void multi() { try { String requestPath = "http://localhost:8080/webframe/demo/test/multi"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); FileBody file = new FileBody(new File("d:/a.jpg")); HttpEntity requestEntity = MultipartEntityBuilder.create() .addPart("file", file) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build(); post.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(post); System.out.println("multi返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .body(MultipartEntityBuilder.create() .addPart("file", file) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build()) .execute().returnContent().toString(); System.out.println("multi fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } }
2.6、完整例子
package com.inspur.demo.http; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; 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.InputStreamEntity; import org.apache.http.entity.StringEntity; 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; /** * 通过Commons-HttpClient调用Http接口 * */ public class HttpClientCase { /** * GET请求 */ public static void get() { try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8"); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet(requestPath); CloseableHttpResponse response = httpClient.execute(get); System.out.println("GET返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Get(requestPath).execute().returnContent().toString(); System.out.println("GET fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } } /** * POST请求(发送键值对数据) */ public static void post() { try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("userId", "1000")); list.add(new BasicNameValuePair("userName", "李白")); post.setEntity(new UrlEncodedFormEntity(list, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyForm(Form.form().add("userId", "1000").add("userName", "李白").build(), Charset.forName("utf-8")) .execute().returnContent().toString(); System.out.println("POST fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } } /** * POST请求(发送json数据) */ public static void post2() { try { String requestPath = "http://localhost:8080/webframe/demo/test/addUser"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); post.setHeader("Content-type", "application/json"); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; post.setEntity(new StringEntity(param, "utf-8")); CloseableHttpResponse response = httpClient.execute(post); System.out.println("POST json返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .addHeader("Content-type", "application/json") .bodyString(param, ContentType.APPLICATION_JSON) .execute().returnContent().toString(); System.out.println("POST json fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } } /** * 上传文件 */ public static void upload() { try { String requestPath = "http://localhost:8080/webframe/demo/test/upload"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); post.setEntity(new InputStreamEntity(fileInputStream)); CloseableHttpResponse response = httpClient.execute(post); System.out.println("upload返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .bodyStream(new FileInputStream("d:/a.jpg")) .execute().returnContent().toString(); System.out.println("upload fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } } /** * 上传文件及发送键值对数据 */ public static void multi() { try { String requestPath = "http://localhost:8080/webframe/demo/test/multi"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(requestPath); FileBody file = new FileBody(new File("d:/a.jpg")); HttpEntity requestEntity = MultipartEntityBuilder.create() .addPart("file", file) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build(); post.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(post); System.out.println("multi返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Post(requestPath) .body(MultipartEntityBuilder.create() .addPart("file", file) .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build()) .execute().returnContent().toString(); System.out.println("multi fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { get(); post(); post2(); upload(); multi(); } }View Code
原文链接:https://www.cnblogs.com/wuyongyin/p/11933461.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- 国外程序员整理的Java资源大全(全部是干货) 2020-06-12
- 2020年深圳中国平安各部门Java中级面试真题合集(附答案) 2020-06-11
- 2020年java就业前景 2020-06-11
- 04.Java基础语法 2020-06-11
- Java--反射(框架设计的灵魂)案例 2020-06-11
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash