httppost的用法

(一)案例一

定义了一个list,该list的数据类型是NameValuePair(简单名称值对节点类型),这个代码多处用于Java像url发送Post请求。在发送post请求时用该list来存放参数。发送请求的大致过程如下:

String url="http://www.baidu.com";
HttpPost httppost=new HttpPost(url); //建立HttpPost对象
List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一个NameValuePair数组,用于存储欲传送的参数
params.add(new BasicNameValuePair("pwd","2544"));
//添加参数
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//设置编码
HttpResponse response=new DefaultHttpClient().execute(httppost);
//发送Post,并返回一个HttpResponse对象
(二)案例二
/** 
     * 获得HttpPost对象 
     *  
     * @param url 
     *            请求地址 
     * @param params 
     *            请求参数 
     * @param encode 
     *            编码方式 
     * @return HttpPost对象 
     * @throws UnsupportedEncodingException 
     */  
    private static HttpPost getHttpPost(String url, Map<String, String> params,  
            String encode) throws UnsupportedEncodingException {  
        HttpPost httpPost = new HttpPost(url);  
        if (params != null) {  
            List<NameValuePair> form = new ArrayList<NameValuePair>();  
            for (String name : params.keySet()) {  
                form.add(new BasicNameValuePair(name, params.get(name)));  
            }
            
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,  
                    encode);  
            httpPost.setEntity(entity);  
        }
        
        return httpPost;  
    }
(三)总结
httpPost其实在服务端模拟浏览器向其它接口发送服务的,一般情况下和httpclient,或者jsonp联合使用,可以把它理解为浏览器就行了,

里面封装了http协议的一些东西,所以要对http协议有一定的了解。

转载自:https://www.cnblogs.com/qingruihappy/p/7817958.html


猜你喜欢

转载自blog.csdn.net/x_nuo/article/details/80339224