httpclient完整实例(普通参数、json格式参数)
时间: 2023-09-06 13:00:34 浏览: 100
HttpClient是一个开源的HTTP客户端库,支持发送HTTP请求和接收HTTP响应。使用HttpClient可以方便地实现与服务器的通信。
普通参数的HttpClient实例可以按照以下步骤进行:
1. 创建HttpClient对象:HttpClient httpClient = new DefaultHttpClient();
2. 创建请求方法对象:HttpGet httpGet = new HttpGet(url);
3. 添加请求参数:
- 对于GET请求,可以将参数添加到URL中,例如:url = url + "?key1=value1&key2=value2"
- 对于POST请求,可以使用NameValuePair将参数封装为键值对,例如:List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("key1", "value1")); params.add(new BasicNameValuePair("key2", "value2"));
4. 将请求参数添加到请求方法中:httpGet.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
5. 发送请求并获取响应:HttpResponse response = httpClient.execute(httpGet);
6. 处理响应结果:
- 获取响应状态码:int statusCode = response.getStatusLine().getStatusCode();
- 获取响应内容:HttpEntity responseEntity = response.getEntity(); String result = EntityUtils.toString(responseEntity);
Json格式参数的HttpClient实例略有不同,可以按照以下步骤进行:
1. 创建HttpClient对象:HttpClient httpClient = new DefaultHttpClient();
2. 创建请求方法对象:HttpPost httpPost = new HttpPost(url);
3. 创建JSON对象并设置参数:JSONObject json = new JSONObject(); json.put("key1", "value1"); json.put("key2", "value2");
4. 将JSON对象转换为字符串并设置请求参数:StringEntity entity = new StringEntity(json.toString(), "UTF-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json");
httpPost.setEntity(entity);
5. 发送请求并获取响应:HttpResponse response = httpClient.execute(httpPost);
6. 处理响应结果:
- 获取响应状态码:int statusCode = response.getStatusLine().getStatusCode();
- 获取响应内容:HttpEntity responseEntity = response.getEntity(); String result = EntityUtils.toString(responseEntity);
上述就是使用HttpClient进行发送HTTP请求和接收HTTP响应的完整实例,分别针对普通参数和JSON格式参数进行了解释。根据具体的项目需求,可以选择适合的方式来进行参数的设置和请求的发送。
阅读全文