http工具类

封装好的http工具类,方便以后使用 

  1. package com.wzm.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.net.URI;  
  7. import java.util.ArrayList;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import org.apache.http.HttpEntity;  
  13. import org.apache.http.HttpResponse;  
  14. import org.apache.http.HttpStatus;  
  15. import org.apache.http.NameValuePair;  
  16. import org.apache.http.StatusLine;  
  17. import org.apache.http.client.HttpClient;  
  18. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  19. import org.apache.http.client.methods.CloseableHttpResponse;  
  20. import org.apache.http.client.methods.HttpGet;  
  21. import org.apache.http.client.methods.HttpPost;  
  22. import org.apache.http.entity.StringEntity;  
  23. import org.apache.http.impl.client.CloseableHttpClient;  
  24. import org.apache.http.impl.client.DefaultHttpClient;  
  25. import org.apache.http.impl.client.HttpClients;  
  26. import org.apache.http.message.BasicNameValuePair;  
  27. import org.apache.http.protocol.HTTP;  
  28. import org.apache.http.util.EntityUtils;  

  29. public class HttpUtil {  
  30.       
  31.     private static Logger logger = Logger.getLogger(HttpUtil.class);  
  32.   
  33.     /** 
  34.      * get请求 
  35.      * @return 
  36.      */  
  37.     public static String doGet(String url) {  
  38.         try {  
  39.             HttpClient client = new DefaultHttpClient();  
  40.             //发送get请求  
  41.             HttpGet request = new HttpGet(url);  
  42.             HttpResponse response = client.execute(request);  
  43.    
  44.             /**请求发送成功,并得到响应**/  
  45.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  46.                 /**读取服务器返回过来的json字符串数据**/  
  47.                 String strResult = EntityUtils.toString(response.getEntity());  
  48.                   
  49.                 return strResult;  
  50.             }  
  51.         }   
  52.         catch (IOException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.           
  56.         return null;  
  57.     }  
  58.       
  59.     /** 
  60.      * post请求(用于key-value格式的参数) 
  61.      * @param url 
  62.      * @param params 
  63.      * @return 
  64.      */  
  65.     public static String doPost(String url, Map params){  
  66.           
  67.         BufferedReader in = null;    
  68.         try {    
  69.             // 定义HttpClient    
  70.             HttpClient client = new DefaultHttpClient();    
  71.             // 实例化HTTP方法    
  72.             HttpPost request = new HttpPost();    
  73.             request.setURI(new URI(url));  
  74.               
  75.             //设置参数  
  76.             List<NameValuePair> nvps = new ArrayList<NameValuePair>();   
  77.             for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {  
  78.                 String name = (String) iter.next();  
  79.                 String value = String.valueOf(params.get(name));  
  80.                 nvps.add(new BasicNameValuePair(name, value));  
  81.             }  
  82.             request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));  
  83.               
  84.             HttpResponse response = client.execute(request);    
  85.             int code = response.getStatusLine().getStatusCode();  
  86.             if(code == 200){    //请求成功  
  87.                 in = new BufferedReader(new InputStreamReader(response.getEntity()    
  88.                         .getContent(),"utf-8"));  
  89.                 StringBuffer sb = new StringBuffer("");    
  90.                 String line = "";    
  91.                 String NL = System.getProperty("line.separator");    
  92.                 while ((line = in.readLine()) != null) {    
  93.                     sb.append(line + NL);    
  94.                 }  
  95.                   
  96.                 in.close();    
  97.                   
  98.                 return sb.toString();  
  99.             }  
  100.             else{   //  
  101.                 System.out.println("请求失败,状态码:" + code);  
  102.                 return null;  
  103.             }  
  104.         }  
  105.         catch(Exception e){  
  106.             e.printStackTrace();  
  107.               
  108.             return null;  
  109.         }  
  110.     }  
  111.       
  112.     /** 
  113.      * post请求(用于请求json格式的参数) 
  114.      * @param url 
  115.      * @param params 
  116.      * @return 
  117.      */  
  118.     public static String doPost(String url, String params) throws Exception {  
  119.           
  120.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  121.         HttpPost httpPost = new HttpPost(url);// 创建httpPost     
  122.         httpPost.setHeader("Accept""application/json");   
  123.         httpPost.setHeader("Content-Type""application/json");  
  124.         String charSet = "UTF-8";  
  125.         StringEntity entity = new StringEntity(params, charSet);  
  126.         httpPost.setEntity(entity);          
  127.         CloseableHttpResponse response = null;  
  128.           
  129.         try {  
  130.               
  131.             response = httpclient.execute(httpPost);  
  132.             StatusLine status = response.getStatusLine();  
  133.             int state = status.getStatusCode();  
  134.             if (state == HttpStatus.SC_OK) {  
  135.                 HttpEntity responseEntity = response.getEntity();  
  136.                 String jsonString = EntityUtils.toString(responseEntity);  
  137.                 return jsonString;  
  138.             }  
  139.             else{  
  140.            
  141.                 System.out.println("请求返回:"+state+"("+url+")");
  142.             }  
  143.         }  
  144.         finally {  
  145.             if (response != null) {  
  146.                 try {  
  147.                     response.close();  
  148.                 } catch (IOException e) {  
  149.                     e.printStackTrace();  
  150.                 }  
  151.             }  
  152.             try {  
  153.                 httpclient.close();  
  154.             } catch (IOException e) {  
  155.                 e.printStackTrace();  
  156.             }  
  157.         }  
  158.         return null;  
  159.     }  
  160.       
  161. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值