HttpClient请求

1.需要引入的几个jar:

httpclient-4.5.2.jar
httpcore-4.4.4.jar
json-lib-2.4-jdk15.jar

2.具体代码:

  CloseableHttpClient httpclient = HttpClients.createDefault();
		
		HttpPost httpPost = new HttpPost(Uri);//uri为请求路径
		
		//头信息
		httpPost.addHeader("X-Auth-Token", "testtesttesttest");
		httpPost.addHeader("Accept", "application/json;chartset=utf-8");
	
		
		// 接收参数json列表  
        JSONObject jsonParam = new JSONObject();  
        jsonParam.put("参数1", "参数1");
        jsonParam.put("参数2","参数2");
    
        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题    
        entity.setContentEncoding("UTF-8");    
        entity.setContentType("application/json");    
        httpPost.setEntity(entity);  


		CloseableHttpResponse response = httpclient.execute(httpPost);

		try {
			int codeStatus = response.getStatusLine().getStatusCode();  //请求结果状态值
			if(codeStatus != 200){
				return;
			}
		   
		    Header[] headers = loginResponse.getAllHeaders();  //响应头信息
		    for(Header header : headers){
		    	String name = header.getName();
		    	String value = header.getValue();
		    }
			//获取返回值:
			HttpEntity entity = response.getEntity();
			String content = EntityUtils.toString(entity,"UTF-8").trim();
		   	
		} catch (UnsupportedOperationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
		    try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					httpclient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
3.参考文章:

(1)http://hc.apache.org/httpclient-3.x/

(2)http://blog.csdn.net/p793049488/article/details/38731883

(3)http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html

(4)http://blog.csdn.net/wangpeng047/article/details/19624529


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值