NameValuePair方式傳參數(shù)

NameValuePair方式傳參數(shù)

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

NameValuePair是簡單名稱值對節(jié)點類型。多用于Java像url發(fā)送Post請求。在發(fā)送post請求時用該list來存放參數(shù)。
例如:
String url="訪問網(wǎng)址";
HttpPost httppost=new HttpPost(url); //建立HttpPost對象
//建立一個NameValuePair數(shù)組,用于存儲傳送的數(shù)據(jù)
List<NameValuePair> params=new ArrayList<NameValuePair>();
//添加參數(shù)
params.add(new BasicNameValuePair("鍵","值"));
//設(shè)置編碼
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//發(fā)送Post,并返回一個HttpResponse對象
HttpResponse response=new DefaultHttpClient().execute(httppost);

調(diào)用

image.png

測試

image.png
    
    public static void main(String[] args) {
        JSONObject object = new JSONObject();
        object.put("account", "0571000448");
        object.put("call", "0");
        object.put("orderNo", "00000000");
        object.put("prodCode", "700034");
        System.out.println(object.toJSONString());
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        StringBuffer builder = new StringBuffer();
        nameValuePairs.add(new BasicNameValuePair("data", object.toJSONString()));
        builder.append("http://10.255.247.77:9094/tyEgral/front/call/saveOrder.do");
        JSONObject result  = HttpUtils.getJson(builder.toString(), nameValuePairs);
    }

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發(fā)送請求、接收響應(yīng)很簡單,一般需要如下幾步即可。
 * 1. 創(chuàng)建HttpClient對象。
 * 2. 創(chuàng)建請求方法的實例,并指定請求URL。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象;如果需要發(fā)送POST請求,創(chuàng)建HttpPost對象。
 * 3. 如果需要發(fā)送請求參數(shù),可調(diào)用HttpGet、HttpPost共同的setParams(HttpParams params)方法來添加請求參數(shù);對于HttpPost對象而言,也可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)。
 * 4. 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求,該方法返回一個HttpResponse。
 * 5. 調(diào)用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭;調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容。
 * 6. 釋放連接。無論執(zhí)行方法是否成功,都必須釋放連接
 */
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的數(shù)據(jù)類型是NameValuePair(簡單名稱值對節(jié)點類型),
         * 這個代碼用于Java像url發(fā)送Post請求。在發(fā)送post請求時用該list來存放參數(shù)。
         */
        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);
                // 判斷網(wǎng)絡(luò)連接狀態(tài)碼是否正常(0--200都數(shù)正常)
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject jsonObject = JSON.parseObject(content);
                    System.out.println("報價返回內(nèi)容是:" + jsonObject.toString());
                    if ("SUCCESS".equals(jsonObject.getString("code"))) {
                        System.out.println("成功,系統(tǒng)處理正常");
                    }
                }
                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();
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容