httpclient UrlEncodedFormEntity

UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容,下面以注册的时候传递的参数为例:

注册的时候写的一个异步线程:


  1. private void registe()  
  2. {  
  3.     new Thread(new Runnable() {  
  4.           
  5.         @Override  
  6.         public void run() {  
  7.             // TODO Auto-generated method stub  
  8.             ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();//用来存放post请求的参数,前面一个键,后面一个值  
  9.             data.add(new BasicNameValuePair(“username”, username));//把昵称放进去  
  10.             data.add(new BasicNameValuePair(“password”, password));//把密码放进去  
  11.             handler.sendMessage(handler.obtainMessage(100,httpTools.doPost(Constants.URL_REGISTE, data)));//发送一个handler消息(100),后面的参数为发送的result,是执行异步请求后返回的结果值  
  12.         }  
  13.     }).start();  
  14. }  
    private void registe()
    {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();//用来存放post请求的参数,前面一个键,后面一个值
                data.add(new BasicNameValuePair("username", username));//把昵称放进去
                data.add(new BasicNameValuePair("password", password));//把密码放进去
                handler.sendMessage(handler.obtainMessage(100,httpTools.doPost(Constants.URL_REGISTE, data)));//发送一个handler消息(100),后面的参数为发送的result,是执行异步请求后返回的结果值
            }
        }).start();
    }

两个键值对,被UrlEncodedFormEntity实例编码后变为如下内容:

param1=value1&param2=value2


然后看下doPost方法:

  1. public String doPost(String url, ArrayList<BasicNameValuePair> data) {  
  2.   
  3.     try {  
  4.         //UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容  
  5.         //两个键值对,被UrlEncodedFormEntity实例编码后变为如下内容:param1=value1¶m2=value2  
  6.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data,  
  7.                 HTTP.UTF_8);//首先将参数设置为utf-8的形式,  
  8.         String result = ”“;//向服务器请求之后返回的数据结果  
  9.         HttpClient httpClient = new DefaultHttpClient();//申明一个网络访问客户端  
  10.         HttpPost post = new HttpPost(url);//post方式  
  11.         post.setEntity(entity);//带上参数  
  12.         HttpResponse httpResponse = httpClient.execute(post);//响应结果  
  13.         if (httpResponse.getStatusLine().getStatusCode() == 200) {//如果是200  表示成功  
  14.             result = EntityUtils.toString(httpResponse.getEntity());//把结果取出来  是一个STRING类型的  
  15.         }  
  16.   
  17.         return result;  
  18.     } catch (Exception e) {  
  19.         Log.i(”post_exception”, e.toString());  
  20.         return null;  
  21.     }  
  22. }  
  public String doPost(String url, ArrayList<BasicNameValuePair> data) {

        try {
            //UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容
            //两个键值对,被UrlEncodedFormEntity实例编码后变为如下内容:param1=value1¶m2=value2
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data,
                    HTTP.UTF_8);//首先将参数设置为utf-8的形式,
            String result = "";//向服务器请求之后返回的数据结果
            HttpClient httpClient = new DefaultHttpClient();//申明一个网络访问客户端
            HttpPost post = new HttpPost(url);//post方式
            post.setEntity(entity);//带上参数
            HttpResponse httpResponse = httpClient.execute(post);//响应结果
            if (httpResponse.getStatusLine().getStatusCode() == 200) {//如果是200  表示成功
                result = EntityUtils.toString(httpResponse.getEntity());//把结果取出来  是一个STRING类型的
            }

            return result;
        } catch (Exception e) {
            Log.i("post_exception", e.toString());
            return null;
        }
    }

我的代码就这些  下面的参考代码:

  1. package com.example.helloandroidhttp;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.net.URLEncoder;  
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12.   
  13. import org.apache.http.HttpEntity;  
  14. import org.apache.http.HttpResponse;  
  15. import org.apache.http.NameValuePair;  
  16. import org.apache.http.client.HttpClient;  
  17. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  18. import org.apache.http.client.methods.HttpGet;  
  19. import org.apache.http.client.methods.HttpPost;  
  20. import org.apache.http.entity.ByteArrayEntity;  
  21. import org.apache.http.entity.StringEntity;  
  22. import org.apache.http.impl.client.DefaultHttpClient;  
  23. import org.apache.http.message.BasicNameValuePair;  
  24. import org.apache.http.params.BasicHttpParams;  
  25. import org.apache.http.params.HttpConnectionParams;  
  26. import org.apache.http.params.HttpParams;  
  27.   
  28. import android.util.Log;  
  29.   
  30. public class HttpUtilsApache {  
  31.   
  32.     private static final String LOG_TAG = “Http->Apache”;  
  33.     private static final String HEADER_CONTENT_TYPE = “Content-Type”;  
  34.     /** 
  35.      * Default encoding for POST or PUT parameters. See 
  36.      * {@link #getParamsEncoding()}. 
  37.      */  
  38.     private static final String DEFAULT_PARAMS_ENCODING = “UTF-8”;  
  39.   
  40.     /** 
  41.      * Returns which encoding should be used when converting POST or PUT 
  42.      * parameters returned by {@link #getParams()} into a raw POST or PUT body. 
  43.      * 
  44.      * <p> 
  45.      * This controls both encodings: 
  46.      * <ol> 
  47.      * <li>The string encoding used when converting parameter names and values 
  48.      * into bytes prior to URL encoding them.</li> 
  49.      * <li>The string encoding used when converting the URL encoded parameters 
  50.      * into a raw byte array.</li> 
  51.      * </ol> 
  52.      */  
  53.     public static String getParamsEncoding() {  
  54.         return DEFAULT_PARAMS_ENCODING;  
  55.     }  
  56.   
  57.     public static String getBodyContentType() {  
  58.         return “application/x-www-form-urlencoded; charset=”  
  59.                 + getParamsEncoding();  
  60.     }  
  61.   
  62.     public static String performGetRequest(String url) {  
  63.   
  64.         String result = null;  
  65.         // 生成一个请求对象  
  66.         HttpGet httpGet = new HttpGet(url);  
  67.   
  68.         // 1.生成一个Http客户端对象(带参数的)  
  69.         HttpParams httpParameters = new BasicHttpParams();  
  70.         HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);// 设置请求超时10秒  
  71.         HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000); // 设置等待数据超时10秒  
  72.         HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);  
  73.   
  74.         HttpClient httpClient = new DefaultHttpClient(httpParameters); // 此时构造DefaultHttpClient时将参数传入  
  75.         // 2.默认实现:  
  76.         // HttpClient httpClient = new DefaultHttpClient();  
  77.         httpGet.addHeader(HEADER_CONTENT_TYPE, getBodyContentType());  
  78.   
  79.         // 下面使用Http客户端发送请求,并获取响应内容  
  80.   
  81.         HttpResponse httpResponse = null;  
  82.   
  83.         try {  
  84.             // 发送请求并获得响应对象  
  85.             httpResponse = httpClient.execute(httpGet);  
  86.   
  87.             final int statusCode = httpResponse.getStatusLine().getStatusCode();  
  88.             if (200 == statusCode) {  
  89.                 result = getResponseString(httpResponse);  
  90.             }  
  91.             else {  
  92.                 Log.e(LOG_TAG, ”Connection failed: ” + statusCode);  
  93.             }  
  94.   
  95.         }  
  96.         catch (Exception e) {  
  97.             e.printStackTrace();  
  98.         }  
  99.         finally {  
  100.   
  101.         }  
  102.   
  103.         return result;  
  104.     }  
  105.   
  106.     public static String performPostRequest(String baseURL, String postData) {  
  107.         String result = ”“;  
  108.         HttpResponse response = null;  
  109.         try {  
  110.   
  111.             // URL使用基本URL即可,其中不需要加参数  
  112.             HttpPost httpPost = new HttpPost(baseURL);  
  113.             // 设置ContentType  
  114.             httpPost.addHeader(HEADER_CONTENT_TYPE, getBodyContentType());  
  115.   
  116.             // 将请求体内容加入请求中  
  117.             HttpEntity requestHttpEntity = prepareHttpEntity(postData);  
  118.   
  119.             if (null != requestHttpEntity) {  
  120.                 httpPost.setEntity(requestHttpEntity);  
  121.             }  
  122.   
  123.             // 需要客户端对象来发送请求  
  124.             HttpClient httpClient = new DefaultHttpClient();  
  125.             // 发送请求  
  126.             response = httpClient.execute(httpPost);  
  127.   
  128.             final int statusCode = response.getStatusLine().getStatusCode();  
  129.             if (200 == statusCode) {  
  130.                 // 显示响应  
  131.                 result = getResponseString(response);  
  132.             }  
  133.             else {  
  134.                 Log.e(LOG_TAG, ”Connection failed: ” + statusCode);  
  135.             }  
  136.   
  137.         }  
  138.         catch (Exception e) {  
  139.             e.printStackTrace();  
  140.         }  
  141.         finally {  
  142.   
  143.         }  
  144.   
  145.         return result;  
  146.   
  147.     }  
  148.   
  149.     /** 
  150.      * 直接利用String生成HttpEntity,String应该已经是key=value&key2=value2的形式 
  151.      * 
  152.      * @param postData 
  153.      * @return 
  154.      */  
  155.     private static HttpEntity prepareHttpEntity(String postData) {  
  156.   
  157.         HttpEntity requestHttpEntity = null;  
  158.   
  159.         try {  
  160.   
  161.             if (null != postData) {  
  162.                 // 去掉所有的换行  
  163.                 postData = postData.replace(”\n”“”);  
  164.                 // one way  
  165.                 // requestHttpEntity = new ByteArrayEntity(  
  166.                 // postData.getBytes(getParamsEncoding()));  
  167.   
  168.                 // another way  
  169.                 requestHttpEntity = new StringEntity(postData,  
  170.                         getParamsEncoding());  
  171.                 ((StringEntity) requestHttpEntity)  
  172.                         .setContentEncoding(getParamsEncoding());  
  173.                 ((StringEntity) requestHttpEntity)  
  174.                         .setContentType(getBodyContentType());  
  175.   
  176.             }  
  177.         }  
  178.         catch (Exception e) {  
  179.             e.printStackTrace();  
  180.         }  
  181.         return requestHttpEntity;  
  182.     }  
  183.   
  184.     /** 
  185.      * 利用Map结构的参数生成HttpEntity,使用UrlEncodedFormEntity对参数对进行编码 
  186.      * 
  187.      * @param params 
  188.      * @return 
  189.      */  
  190.     private static HttpEntity prepareHttpEntity1(Map<String, String> params) {  
  191.         // 需要将String里面的key value拆分出来  
  192.   
  193.         HttpEntity requestHttpEntity = null;  
  194.         try {  
  195.   
  196.             if (null != params) {  
  197.                 List<NameValuePair> pairList = new ArrayList<NameValuePair>(  
  198.                         params.size());  
  199.                 for (Map.Entry<String, String> entry : params.entrySet()) {  
  200.                     NameValuePair pair = new BasicNameValuePair(entry.getKey(),  
  201.                             entry.getValue());  
  202.                     pairList.add(pair);  
  203.                 }  
  204.                 requestHttpEntity = new UrlEncodedFormEntity(pairList,  
  205.                         getParamsEncoding());  
  206.   
  207.             }  
  208.   
  209.         }  
  210.         catch (UnsupportedEncodingException e) {  
  211.             e.printStackTrace();  
  212.         }  
  213.   
  214.         return requestHttpEntity;  
  215.     }  
  216.   
  217.     /** 
  218.      * 利用Map结构的参数生成HttpEntity,使用自己的方法对参数进行编码合成字符串 
  219.      * 
  220.      * @param params 
  221.      * @return 
  222.      */  
  223.     private static HttpEntity prepareHttpEntity2(Map<String, String> params) {  
  224.         // 需要将String里面的key value拆分出来  
  225.   
  226.         HttpEntity requestHttpEntity = null;  
  227.         byte[] body = encodeParameters(params, getParamsEncoding());  
  228.         requestHttpEntity = new ByteArrayEntity(body);  
  229.   
  230.         return requestHttpEntity;  
  231.     }  
  232.   
  233.     /** 
  234.      * Converts <code>params</code> into an application/x-www-form-urlencoded 
  235.      * encoded string. 
  236.      */  
  237.     private static byte[] encodeParameters(Map<String, String> params,  
  238.             String paramsEncoding) {  
  239.         StringBuilder encodedParams = new StringBuilder();  
  240.         try {  
  241.             for (Map.Entry<String, String> entry : params.entrySet()) {  
  242.                 encodedParams.append(URLEncoder.encode(entry.getKey(),  
  243.                         paramsEncoding));  
  244.                 encodedParams.append(’=’);  
  245.                 encodedParams.append(URLEncoder.encode(entry.getValue(),  
  246.                         paramsEncoding));  
  247.                 encodedParams.append(’&’);  
  248.             }  
  249.             return encodedParams.toString().getBytes(paramsEncoding);  
  250.         }  
  251.         catch (UnsupportedEncodingException uee) {  
  252.             throw new RuntimeException(“Encoding not supported: ”  
  253.                     + paramsEncoding, uee);  
  254.         }  
  255.     }  
  256.   
  257.     public static String getResponseString(HttpResponse response) {  
  258.         String result = null;  
  259.         if (null == response) {  
  260.             return result;  
  261.         }  
  262.   
  263.         HttpEntity httpEntity = response.getEntity();  
  264.         InputStream inputStream = null;  
  265.         try {  
  266.             inputStream = httpEntity.getContent();  
  267.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
  268.                     inputStream));  
  269.             result = ”“;  
  270.             String line = ”“;  
  271.             while (null != (line = reader.readLine())) {  
  272.                 result += line;  
  273.             }  
  274.         }  
  275.         catch (Exception e) {  
  276.             e.printStackTrace();  
  277.         }  
  278.         finally {  
  279.             try {  
  280.                 if (null != inputStream) {  
  281.                     inputStream.close();  
  282.                 }  
  283.             }  
  284.             catch (IOException e) {  
  285.                 e.printStackTrace();  
  286.             }  
  287.         }  
  288.         return result;  
  289.   
  290.     }  
  291. }  
  292.   
  293. HttpUtilsApache  
package com.example.helloandroidhttp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class HttpUtilsApache {

    private static final String LOG_TAG = "Http->Apache";
    private static final String HEADER_CONTENT_TYPE = "Content-Type";
    /**
     * Default encoding for POST or PUT parameters. See
     * {@link #getParamsEncoding()}.
     */
    private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";

    /**
     * Returns which encoding should be used when converting POST or PUT
     * parameters returned by {@link #getParams()} into a raw POST or PUT body.
     *
     * <p>
     * This controls both encodings:
     * <ol>
     * <li>The string encoding used when converting parameter names and values
     * into bytes prior to URL encoding them.</li>
     * <li>The string encoding used when converting the URL encoded parameters
     * into a raw byte array.</li>
     * </ol>
     */
    public static String getParamsEncoding() {
        return DEFAULT_PARAMS_ENCODING;
    }

    public static String getBodyContentType() {
        return "application/x-www-form-urlencoded; charset="
                + getParamsEncoding();
    }

    public static String performGetRequest(String url) {

        String result = null;
        // 生成一个请求对象
        HttpGet httpGet = new HttpGet(url);

        // 1.生成一个Http客户端对象(带参数的)
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);// 设置请求超时10秒
        HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000); // 设置等待数据超时10秒
        HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);

        HttpClient httpClient = new DefaultHttpClient(httpParameters); // 此时构造DefaultHttpClient时将参数传入
        // 2.默认实现:
        // HttpClient httpClient = new DefaultHttpClient();
        httpGet.addHeader(HEADER_CONTENT_TYPE, getBodyContentType());

        // 下面使用Http客户端发送请求,并获取响应内容

        HttpResponse httpResponse = null;

        try {
            // 发送请求并获得响应对象
            httpResponse = httpClient.execute(httpGet);

            final int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                result = getResponseString(httpResponse);
            }
            else {
                Log.e(LOG_TAG, "Connection failed: " + statusCode);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

        }

        return result;
    }

    public static String performPostRequest(String baseURL, String postData) {
        String result = "";
        HttpResponse response = null;
        try {

            // URL使用基本URL即可,其中不需要加参数
            HttpPost httpPost = new HttpPost(baseURL);
            // 设置ContentType
            httpPost.addHeader(HEADER_CONTENT_TYPE, getBodyContentType());

            // 将请求体内容加入请求中
            HttpEntity requestHttpEntity = prepareHttpEntity(postData);

            if (null != requestHttpEntity) {
                httpPost.setEntity(requestHttpEntity);
            }

            // 需要客户端对象来发送请求
            HttpClient httpClient = new DefaultHttpClient();
            // 发送请求
            response = httpClient.execute(httpPost);

            final int statusCode = response.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                // 显示响应
                result = getResponseString(response);
            }
            else {
                Log.e(LOG_TAG, "Connection failed: " + statusCode);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

        }

        return result;

    }

    /**
     * 直接利用String生成HttpEntity,String应该已经是key=value&key2=value2的形式
     *
     * @param postData
     * @return
     */
    private static HttpEntity prepareHttpEntity(String postData) {

        HttpEntity requestHttpEntity = null;

        try {

            if (null != postData) {
                // 去掉所有的换行
                postData = postData.replace("\n", "");
                // one way
                // requestHttpEntity = new ByteArrayEntity(
                // postData.getBytes(getParamsEncoding()));

                // another way
                requestHttpEntity = new StringEntity(postData,
                        getParamsEncoding());
                ((StringEntity) requestHttpEntity)
                        .setContentEncoding(getParamsEncoding());
                ((StringEntity) requestHttpEntity)
                        .setContentType(getBodyContentType());

            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return requestHttpEntity;
    }

    /**
     * 利用Map结构的参数生成HttpEntity,使用UrlEncodedFormEntity对参数对进行编码
     *
     * @param params
     * @return
     */
    private static HttpEntity prepareHttpEntity1(Map<String, String> params) {
        // 需要将String里面的key value拆分出来

        HttpEntity requestHttpEntity = null;
        try {

            if (null != params) {
                List<NameValuePair> pairList = new ArrayList<NameValuePair>(
                        params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(entry.getKey(),
                            entry.getValue());
                    pairList.add(pair);
                }
                requestHttpEntity = new UrlEncodedFormEntity(pairList,
                        getParamsEncoding());

            }

        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return requestHttpEntity;
    }

    /**
     * 利用Map结构的参数生成HttpEntity,使用自己的方法对参数进行编码合成字符串
     *
     * @param params
     * @return
     */
    private static HttpEntity prepareHttpEntity2(Map<String, String> params) {
        // 需要将String里面的key value拆分出来

        HttpEntity requestHttpEntity = null;
        byte[] body = encodeParameters(params, getParamsEncoding());
        requestHttpEntity = new ByteArrayEntity(body);

        return requestHttpEntity;
    }

    /**
     * Converts <code>params</code> into an application/x-www-form-urlencoded
     * encoded string.
     */
    private static byte[] encodeParameters(Map<String, String> params,
            String paramsEncoding) {
        StringBuilder encodedParams = new StringBuilder();
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                encodedParams.append(URLEncoder.encode(entry.getKey(),
                        paramsEncoding));
                encodedParams.append('=');
                encodedParams.append(URLEncoder.encode(entry.getValue(),
                        paramsEncoding));
                encodedParams.append('&');
            }
            return encodedParams.toString().getBytes(paramsEncoding);
        }
        catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: "
                    + paramsEncoding, uee);
        }
    }

    public static String getResponseString(HttpResponse response) {
        String result = null;
        if (null == response) {
            return result;
        }

        HttpEntity httpEntity = response.getEntity();
        InputStream inputStream = null;
        try {
            inputStream = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream));
            result = "";
            String line = "";
            while (null != (line = reader.readLine())) {
                result += line;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }
}

HttpUtilsApache


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值