zoukankan      html  css  js  c++  java
  • java 封装httpclient 的get 和post 请求

      1 import java.io.ByteArrayOutputStream;
      2 import java.io.UnsupportedEncodingException;
      3 import java.util.ArrayList;
      4 import java.util.Iterator;
      5 import java.util.List;
      6 import java.util.Map;
      7 import java.util.Map.Entry;
      8 import java.util.Set;
      9 
     10 import org.apache.http.HttpEntity;
     11 import org.apache.http.HttpResponse;
     12 import org.apache.http.client.HttpClient;
     13 import org.apache.http.client.entity.UrlEncodedFormEntity;
     14 import org.apache.http.client.methods.HttpGet;
     15 import org.apache.http.client.methods.HttpPost;
     16 import org.apache.http.client.methods.HttpPut;
     17 import org.apache.http.entity.BufferedHttpEntity;
     18 import org.apache.http.impl.client.DefaultHttpClient;
     19 import org.apache.http.message.BasicNameValuePair;
     20 
     21 public class HttpUtil {
     22 
     23     /**
     24      * 以Post方法访问
     25      * @param url 请求地址
     26      * @param paramsMap 携带的参数
     27      * @return  String 返回结果
     28      * @throws Exception
     29      */
     30     @SuppressWarnings("deprecation")
     31     public static String postMethod(String url, Map<String, Object> paramsMap){
     32         String result = "SUCCESS";
     33         try {
     34             byte[] dataByte = null;
     35             HttpClient httpClient = new DefaultHttpClient();
     36             HttpPost httpPost = new HttpPost(url);
     37             UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(setHttpParams(paramsMap), "UTF-8");
     38             httpPost.setEntity(encodedFormEntity);
     39             HttpResponse httpResponse = httpClient.execute(httpPost);
     40             if (!checkNetwork(httpResponse)) {
     41                 result = "LINK FAILURE!";
     42                 return result;
     43             }
     44             HttpEntity httpEntity = httpResponse.getEntity();
     45             if (httpEntity != null) {
     46                 byte[] responseBytes = getData(httpEntity);
     47                 dataByte = responseBytes;
     48                 httpPost.abort();
     49             }
     50             result = bytesToString(dataByte);
     51         } catch (Exception e) {
     52             result = "FAILURE";
     53             e.printStackTrace();
     54         }
     55         return result;
     56     }
     57      
     58     /**
     59      * 以Get方法访问
     60      * @param url 请求地址
     61      */
     62     public static String GETMethod(String url,Map<String, Object> paramsMap){
     63         String result = "SUCCESS";
     64         try{
     65             byte[] dataByte = null;
     66             HttpClient httpClient = new DefaultHttpClient();
     67             //为GET请求链接构造参数
     68             url = formatGetParameter(url,paramsMap);
     69             HttpGet httpGet = new HttpGet(url);
     70             HttpResponse httpResponse = httpClient.execute(httpGet);
     71             if (!checkNetwork(httpResponse)) {
     72                 result = "LINK FAILURE!";
     73                 return result;
     74             }
     75             HttpEntity httpEntity = httpResponse.getEntity();
     76             if (httpEntity != null) {
     77                 byte[] responseBytes = getData(httpEntity);
     78                 dataByte = responseBytes;
     79                 httpGet.abort();
     80             }
     81             result = bytesToString(dataByte);
     82         }catch(Exception e){
     83             result = "LINK FAILURE!";
     84             e.printStackTrace();
     85         }
     86         return result;
     87     }
     88      
     89     /**
     90      * 以Put方法访问
     91      * @param url 请求地址
     92      */
     93     public static String PUTMethod(String url,Map<String, Object> paramsMap){
     94         String result = "SUCCESS";
     95         try {
     96             byte[] dataByte = null;
     97             HttpClient httpClient = new DefaultHttpClient();
     98             HttpPut httpPut = new HttpPut(url);
     99             UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(setHttpParams(paramsMap), "UTF-8");
    100             httpPut.setEntity(encodedFormEntity);
    101             HttpResponse httpResponse = httpClient.execute(httpPut);
    102             if (!checkNetwork(httpResponse)) {
    103                 result = "LINK FAILURE!";
    104                 return result;
    105             }
    106             // 获取返回的数据
    107             HttpEntity httpEntity = httpResponse.getEntity();
    108             if (httpEntity != null) {
    109                 byte[] responseBytes = getData(httpEntity);
    110                 dataByte = responseBytes;
    111                 httpPut.abort();
    112             }
    113             result = bytesToString(dataByte);
    114         } catch (Exception e) {
    115             result = "LINK FAILURE!";
    116             e.printStackTrace();
    117         }
    118         return result;
    119     }
    120      
    121     /**
    122      * 构造GET请求地址的参数拼接
    123      * @param url
    124      * @param paramsMap
    125      * @return String
    126      */
    127     private static String formatGetParameter(String url, Map<String, Object> paramsMap) {
    128         if (paramsMap != null && !paramsMap.isEmpty()) {
    129             if (url != null && url.length() > 0) {
    130                 if (!url.endsWith("?")) {
    131                     url = url + "?";
    132                 }
    133                 Set<Entry<String, Object>> entrySet = paramsMap.entrySet();
    134                 Iterator<Entry<String, Object>> iterator = entrySet.iterator();
    135                 while (iterator.hasNext()) {
    136                     Entry<String, Object> entry = iterator.next();
    137                     if (entry != null) {
    138                         String key = entry.getKey();
    139                         String value = (String) entry.getValue();
    140                         url = url + key + "=" + value;
    141                         if (iterator.hasNext()) {
    142                             url = url + "&";
    143                         }
    144                     }
    145                 }
    146             }
    147         }
    148         return url;
    149     }
    150      
    151     /**
    152      * 获取数据
    153      * @param httpEntity
    154      */
    155     private static byte[] getData(HttpEntity httpEntity) throws Exception{
    156         BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
    157         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    158         bufferedHttpEntity.writeTo(byteArrayOutputStream);
    159         byte[] responseBytes = byteArrayOutputStream.toByteArray();
    160         return responseBytes;
    161     }
    162      
    163     /**
    164      * 设置HttpPost请求参数
    165      * @param paramsMap
    166      * @return BasicHttpParams
    167      */
    168     private static List<BasicNameValuePair> setHttpParams(Map<String, Object> paramsMap){
    169         List<BasicNameValuePair> nameValuePairList = new ArrayList<BasicNameValuePair>();
    170         if (paramsMap!=null && !paramsMap.isEmpty()) {
    171             Set<Entry<String, Object>> set = paramsMap.entrySet();
    172             Iterator<Entry<String, Object>> iterator = set.iterator();
    173             while(iterator.hasNext()){
    174                 Entry<String, Object> entry = iterator.next();
    175                 BasicNameValuePair basicNameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
    176                 nameValuePairList.add(basicNameValuePair);
    177             }
    178         }
    179         return nameValuePairList;
    180     }
    181      
    182     /**
    183      * 将字节数组转换成字符串
    184      * @param bytes
    185      */
    186     private static String bytesToString(byte[] bytes) throws UnsupportedEncodingException{
    187         if (bytes!=null) {
    188             String returnStr = new String(bytes,"utf-8");
    189             return returnStr;
    190         }
    191         return null;
    192     }
    193     
    194     /**
    195      * 判断网络连接是否成功
    196      */
    197     public static boolean checkNetwork(HttpResponse httpResponse){
    198         if (httpResponse.getStatusLine().getStatusCode() == 200) {
    199             return true;
    200         }
    201         return false;
    202     }
    203 }
  • 相关阅读:
    Windows系统 Mysql5.6下载安装以及配置
    【翻译】Javascript “组件模式” 深入研究
    【原创】使用GridView实现绑定List并排序
    【翻译】【项目架构必备】Asp.Net MVC3 定义自己的项目模板
    【原创】也谈我如何解决Silverlight跨域访问安全性问题
    【翻译】MVC 3 Razor语法技巧之——The @helper syntax
    【翻译】Knockout 2.1版本发布&新特性一览
    【原创】三把利器快速制作代码帮助文档
    现代软件工程_团队项目_阿尔法阶段_第二次会议记录_2017.11.13
    现代软件工程_团队项目_阿尔法阶段_需求分析文档_2017.11.13
  • 原文地址:https://www.cnblogs.com/hjwbla/p/5163566.html
Copyright © 2011-2022 走看看