NameValuePair的用法


定義了一個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對象

 

看到有人寫過這個覺得不錯,於是轉載過來當做是備忘錄:https://www.cnblogs.com/hunt/p/7071053.html

 

今天工作中聯調外部的一個接口用post方式傳輸,我按照文檔封裝參數成Jason字符串傳入,但是對方一直接受參數為空,折騰了半天也沒找到問題。很苦惱,檢查代碼都沒有錯誤,可是為什么對方接受參數為空呢?然后找對方的技術人員聯調,看看是怎么回事,也折騰了半天最后發現對方是用NameValuePair方式傳參數。雖然這個方式已經過時了,但是在這里記錄下,以備以后出現類似的方式傳參數。

package com.souche.lease.finance.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hunt on 2017/6/26.
 * 使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可。
 * 1. 創建HttpClient對象。
 * 2. 創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
 * 3. 如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HttpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
 * 4. 調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。
 * 5. 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。
 * 6. 釋放連接。無論執行方法是否成功,都必須釋放連接
 */
public class SDTestDemo {
    public static void main(String[] args) {
        String licenseNo = "浙A588AX";
        String token = "7cc2bd72eb1e4522804dca3b88e8644d";
        String city = "330100";
        String timestamp = Long.toString(System.currentTimeMillis());
        String sign;
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("licenseNo", licenseNo);
        mapParam.put("token", token);
        mapParam.put("city", city);
        mapParam.put("timestamp", timestamp);
        SDTestUtil testUtil = new SDTestUtil();
        sign = testUtil.MD5(testUtil.sort(mapParam));
        mapParam.put("sign", sign);
        /**
         * 定義了一個list,該list的數據類型是NameValuePair(簡單名稱值對節點類型),
         * 這個代碼用於Java像url發送Post請求。在發送post請求時用該list來存放參數。
         */
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("licenseNo", licenseNo));
        urlParameters.add(new BasicNameValuePair("token", token));
        urlParameters.add(new BasicNameValuePair("city", city));
        urlParameters.add(new BasicNameValuePair("timestamp", timestamp));
        urlParameters.add(new BasicNameValuePair("sign", sign));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost post = new HttpPost("http://101.231.154.154:8047/v4.0/renewal");
        try {
            post.setEntity(new UrlEncodedFormEntity(urlParameters, HTTP.UTF_8));
            try {
                response = httpclient.execute(post);
                // 判斷網絡連接狀態碼是否正常(0--200都數正常)
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject jsonObject = JSON.parseObject(content);
                    System.out.println("報價返回內容是:" + jsonObject.toString());
                    if ("SUCCESS".equals(jsonObject.getString("code"))) {
                        System.out.println("成功,系統處理正常");
                    }
                }
                EntityUtils.consume(response.getEntity());//完全消耗
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != response) response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            //釋放鏈接
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM