httpClient使用的工具类

工作的时候用到的,做一次记录,方便以后使用

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;



public class HttpClientUtil {
	
	public static Logger logger = Logger.getLogger(HttpClientUtil.class);
	
	 public String getAccess_token(String corpid,String corpsecret){
	        String urlNameString = "http://webapi.***.com/services/access_token.ashx?corpid=ID&corpsecret=SECRET";
	        urlNameString=urlNameString.replace("ID", corpid);
	        urlNameString=urlNameString.replace("SECRET",corpsecret);
	        String result="";
	          try {
	                // 根据地址获取请求
	                HttpGet request = new HttpGet(urlNameString);//这里发送get请求
	                // 获取当前客户端对象
	                CloseableHttpClient httpclient = HttpClients.createDefault();   
	                // 通过请求对象获取响应对象
	                CloseableHttpResponse response = httpclient.execute(request);
	                
	                // 判断网络连接状态码是否正常(0--200都数正常)
	                if (response.getStatusLine().getStatusCode() == 200) {
	                    result= EntityUtils.toString(response.getEntity(),"utf-8");
	                } 
	            } catch (Exception e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	        return result;
	    }
	 
	 
	  public String post(HashMap<String,String> map,String url) throws HttpHostConnectException, ClientProtocolException, IOException{  
	        String result=null;  
	          CloseableHttpClient httpclient = HttpClients.createDefault();   
	          RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
	            // 创建httppost      
	            HttpPost httppost = new HttpPost(url);    
	            // 创建参数队列      
	            List<NameValuePair> formparams = getNameValuePairListFormModel(map);  
	            UrlEncodedFormEntity uefEntity;    
	            CloseableHttpResponse response = null;  
	                uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");    
	                httppost.setEntity(uefEntity);    
	                httppost.setConfig(requestConfig);    
	                response = httpclient.execute(httppost);    
	                    HttpEntity entity = response.getEntity();    
	                    if (entity != null && response.getStatusLine().getStatusCode()==200) {  
	                        result=EntityUtils.toString(entity, "UTF-8");  
	                    }else if(response.getStatusLine().getStatusCode()==302){  
	                    	Header header = response.getFirstHeader("Location"); // 跳转的目标地址是在 HTTP-HEAD 中的
	                        String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
	                        httppost = new HttpPost(newuri);
	                        httppost.setEntity(uefEntity);  
	                        httppost.setConfig(requestConfig); 
	                        response = httpclient.execute(httppost);
	                        int code = response.getStatusLine().getStatusCode();
	                        entity = response.getEntity();
	                        result=EntityUtils.toString(entity, "UTF-8");  
	                        System.out.println("code:"+code);
	                    }else{
	                    	 logger.info(httppost.getURI()+"  请求出现异常,返回码为:  "+response.getStatusLine().getStatusCode());  
	                    }  
	                    response.close();    
	                // 关闭连接,释放资源      
	                    httpclient.close();    
	            return result;  
	    }  
	      
	      
	    public static List<NameValuePair>  getNameValuePairListFormModel(HashMap<String,String> map){  
	        List<NameValuePair> list=new ArrayList<NameValuePair>();  
	        for(Entry<String, String> entry:map.entrySet()){
	        	 list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	        }
	        return list;  
	    }  
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值