NameValuePair和BasicNameValuePair的关系

NameValuePair

简单名称值对节点类型,多用于java像URL发送post请求,在发送Post请求的时候使用该list来存放参数;

BasicNameValuePair

BasicNameValuePair是实现了apache http的NameValuePair这个接口的类型;

例子:

String url="访问网址";

HttpPost httppost=new HttpPost(url); //建立HttpPost对象

//建立一个NameValuePair数组,用于存储传送的数据

List<NameValuePair> params=new ArrayList<NameValuePair>();

//添加参数(这里我们使用NameValuePair的实现类来创建对象)

params.add(new BasicNameValuePair("键","值"));

//设置编码

httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));

//发送1653Post,并返回一个HttpResponse对象

HttpResponse response=new DefaultHttpClient().execute(httppost);

实战

public String httpPost(Map<String, String> requestParams, String urlEncode) {
        HttpPost httpPost = null;
        String resp = "";
        try {
            // 参数设置
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : requestParams.entrySet()) {
                params.add(new BasicNameValuePair((String) entry.getKey(),
                        (String) entry.getValue()));
            }
 
            httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params, urlEncode));
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) 
            {
                return null;
            }
            HttpEntity httpEntity = response.getEntity();
            resp = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpPost != null) {
                httpPost.abort();
            }
        }
        return resp;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章