HttpClient Get请求带参数

/*
	 * HttpClient Get请求带参数
	 */
	@Test
	public void fun1() throws ClientProtocolException, IOException {
		
//		1、创建httpClient
		CloseableHttpClient client = HttpClients.createDefault();
//		2、封装请求参数
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		list.add(new BasicNameValuePair("username", "cgx"));
		list.add(new BasicNameValuePair("password", "123456"));
		
		//3、转化参数
		String params = EntityUtils.toString(new UrlEncodedFormEntity(list,Consts.UTF_8));
		System.out.println(params);
		//4、创建HttpGet请求
		HttpGet httpGet = new HttpGet("http://localhost:8080/itcast297/loginAction_login"+"?"+params);
		CloseableHttpResponse response = client.execute(httpGet);
		
		//5、获取实体
		HttpEntity entity = response.getEntity();
		//将实体装成字符串
		String string = EntityUtils.toString(entity);
		System.out.println(string);
		
		response.close();
	}
  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 HttpClient 的 `UrlEncodedFormEntity` 类来设置 POST 请求的参数。 以下是一个示例代码: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import java.util.ArrayList; import java.util.List; public class HttpClientExample { public static void main(String[] args) throws Exception { // 创建 HttpClient 对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建 HttpPost 对象 HttpPost httpPost = new HttpPost("http://example.com"); // 设置 POST 请求参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params)); // 发送 POST 请求 CloseableHttpResponse response = httpClient.execute(httpPost); // 处理响应 System.out.println(response.getStatusLine()); httpClient.close(); } } ``` 在这个示例中,我们创建了一个 `HttpPost` 对象,并设置了 POST 请求的 URL 和参数。然后我们使用 `httpClient` 对象发送这个请求,并处理响应。需要注意的是,`UrlEncodedFormEntity` 类将参数编码为 HTML 表单形式,而不是 JSON 或其他格式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值