java HttpClient 发送Http请求

本文介绍如何使用Apache HttpClient库在Java中发出GET和POST请求。通过示例代码展示了如何配置HTTP客户端,创建GET和POST请求,以及如何处理响应。同时,提供了添加额外参数到GET请求的方法。

所需maven jar包

                <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.4.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.1</version>
		</dependency>        

  发出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<NameValuePair> list = new ArrayList<NameValuePair>();
		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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值