簡體   English   中英

commons httpclient - 將查詢字符串參數添加到GET / POST請求

[英]commons httpclient - Adding query string parameters to GET/POST request

我正在使用公共HttpClient對Spring servlet進行http調用。 我需要在查詢字符串中添加一些參數。 所以我做了以下事情:

HttpRequestBase request = new HttpGet(url);
HttpParams params = new BasicHttpParams();
params.setParameter("key1", "value1");
params.setParameter("key2", "value2");
params.setParameter("key3", "value3");
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
httpClient.execute(request);

但是當我嘗試使用servlet讀取參數時

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getParameter("key");

它返回null。 實際上parameterMap是完全空的。 當我在創建HttpGet請求之前手動將參數附加到url時,參數在servlet中可用。 當我使用附加了queryString的URL從瀏覽器中訪問servlet時也是如此。

這里的錯誤是什么? 在httpclient 3.x中,GetMethod有一個setQueryString()方法來追加查詢字符串。 4.x中的等價物是什么?

以下是使用HttpClient 4.2及更高版本添加查詢字符串參數的方法:

URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");

HttpPost post = new HttpPost(builder.build());

生成的URI看起來像:

http://example.com/?parts=all&action=finish

如果要在創建請求后添加查詢參數,請嘗試將HttpRequest強制轉換為HttpBaseRequest 然后,您可以更改已轉換請求的URI:

HttpGet someHttpGet = new HttpGet("http://google.de");

URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
        "That was easy!").build();

((HttpRequestBase) someHttpGet).setURI(uri);

HttpParams接口不用於指定查詢字符串參數,而是用於指定HttpClient對象的運行時行為。

如果要傳遞查詢字符串參數,則需要自己在URL上組裝它們,例如

new HttpGet(url + "key1=" + value1 + ...);

請記住首先對值進行編碼(使用URLEncoder )。

我正在使用httpclient 4.4。

對於solr查詢,我使用以下方式,它工作。

NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
            request.setURI(uri);

HttpResponse response = client.execute(request);    
if (response.getStatusLine().getStatusCode() != 200) {

}

BufferedReader br = new BufferedReader(
                             new InputStreamReader((response.getEntity().getContent())));

String output;
System.out.println("Output  .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
    respStr = respStr + output;
    System.out.println(output);
}

這種方法沒問題,但是當你動態獲取params時有效,有時是1,2,3或更多,就像SOLR搜索查詢一樣(例如)

這是一個更靈活的解決方案。 原油但可以提煉。

public static void main(String[] args) {

    String host = "localhost";
    String port = "9093";

    String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
    String[] wholeString = param.split("\\?");
    String theQueryString = wholeString.length > 1 ? wholeString[1] : "";

    String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";

    GetMethod method = new GetMethod(SolrUrl );

    if (theQueryString.equalsIgnoreCase("")) {
        method.setQueryString(new NameValuePair[]{
        });
    } else {
        String[] paramKeyValuesArray = theQueryString.split("&");
        List<String> list = Arrays.asList(paramKeyValuesArray);
        List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
        for (String s : list) {
            String[] nvPair = s.split("=");
            String theKey = nvPair[0];
            String theValue = nvPair[1];
            NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
            nvPairList.add(nameValuePair);
        }
        NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
        nvPairList.toArray(nvPairArray);
        method.setQueryString(nvPairArray);       // Encoding is taken care of here by setQueryString

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM