博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java HttpClient 发送Http请求
阅读量:5144 次
发布时间:2019-06-13

本文共 2126 字,大约阅读时间需要 7 分钟。

所需maven jar包

org.apache.httpcomponents
httpclient
4.4.1
org.apache.httpcomponents
httpcore
4.4.1

  发出get请求,可调用外部rest接口:

@org.junit.Test	public void testGet() throws IOException, Exception {		//创建HttpClient客户端		CloseableHttpClient httpClient = HttpClients.createDefault();		//创建请求方式  post  get  http://localhost:8888/demo/test/				String uri = "http://localhost:8888/demo/test/hello/cc/a";		HttpGet httpGet = new HttpGet(uri);		CloseableHttpResponse response = httpClient.execute(httpGet);		//相应结果		int statusCode = response.getStatusLine().getStatusCode();		System.out.println(statusCode);				HttpEntity entity = response.getEntity();				String string = EntityUtils.toString(entity);				System.out.println(string);				response.close();		httpClient.close();			}

  发出post请求,模拟表单发请求:

@org.junit.Test	public void testPost() throws IOException, Exception {		//创建HttpClient客户端		CloseableHttpClient httpClient = HttpClients.createDefault();		//创建请求方式  post  get  				String uri = "http://localhost:8888/demo/test/testPost";		HttpPost httpPost = new HttpPost(uri);				//创建一个Entity,模拟一个表单		List
list = new ArrayList
(); list.add(new BasicNameValuePair("id", "1001")); list.add(new BasicNameValuePair("name", "小黑")); //把表单包装成一个HttpEntity对象 HttpEntity stringEntity = new UrlEncodedFormEntity(list,"utf-8"); //设置请求的内容 httpPost.setEntity(stringEntity); CloseableHttpResponse response = httpClient.execute(httpPost); //相应结果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity); System.out.println(string); response.close(); httpClient.close(); }

  get请求添加其他参数,可参照:

//创建一个uri对象URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");uriBuilder.addParameter("query","花千骨");HttpGet get = new HttpGet(uriBuilder.build());

  

转载于:https://www.cnblogs.com/blog411032/p/9718990.html

你可能感兴趣的文章
spring IOC装配Bean(注解方式)
查看>>
[面试算法题]有序列表删除节点-leetcode学习之旅(4)
查看>>
SpringBoot系列五:SpringBoot错误处理(数据验证、处理错误页、全局异常)
查看>>
kubernetes_book
查看>>
OpenFire 的安装和配置
查看>>
侧边栏广告和回到顶部
查看>>
https://blog.csdn.net/u012106306/article/details/80760744
查看>>
ios应用版本号设置规则
查看>>
海上孤独的帆
查看>>
error: more than one device and emulator 问题解决
查看>>
springmvc集成Freemarke配置的几点
查看>>
Django 学习
查看>>
Linux-socket的close和shutdown区别及应用场景
查看>>
xpath
查看>>
parted分区
查看>>
图片标签img
查看>>
表哥的Access入门++以Excel视角快速学习数据库知识pdf
查看>>
TC 配置插件
查看>>
关于异步reset
查看>>
索引优先队列的工作原理与简易实现
查看>>