commons httpclient—添加查询字符串参数以获取/POST请求

时间:2021-08-11 20:29:49

I am using commons HttpClient to make an http call to a Spring servlet. I need to add a few parameters in the query string. So I do the following:

我正在使用commons 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);

However when i try to read the parameter in the servlet using

但是,当我尝试使用servlet读取参数时

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

it returns null. In fact the parameterMap is completely empty. When I manually append the parameters to the url before creating the HttpGet request, the parameters are available in the servlet. Same when I hit the servlet from the browser using the URL with queryString appended.

它会返回null。实际上,参数映射是完全空的。当我在创建HttpGet请求之前手动将参数附加到url时,这些参数在servlet中是可用的。当我使用附加了queryString的URL从浏览器点击servlet时也是一样的。

What's the error here? In httpclient 3.x, GetMethod had a setQueryString() method to append the querystring. What's the equivalent in 4.x?

这里的错误是什么?httpclient 3。GetMethod有一个setQueryString()方法来附加querystring。4。x等于多少?

5 个解决方案

#1


65  

Here is how you would add query string parameters using HttpClient 4.2 and later:

下面是如何使用HttpClient 4.2和稍后添加查询字符串参数的方法:

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

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

The resulting URI would look like:

产生的URI如下所示:

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

#2


23  

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

如果希望在创建请求之后添加查询参数,请尝试将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);

#3


10  

The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

HttpParams接口没有用于指定查询字符串参数,而是用于指定HttpClient对象的运行时行为。

If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.

如果你想传递查询字符串参数,你需要自己在URL上组装它们。

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

Remember to encode the values first (using URLEncoder).

记住先对值进行编码(使用URLEncoder)。

#4


3  

I am using httpclient 4.4.

我正在使用httpclient 4.4。

For solr query I used the following way and it worked.

对于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);
}

#5


1  

This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)

这种方法是可行的,但是当你动态地获得params时,有时是1、2、3或更多,就像SOLR搜索查询(例如)

Here is a more flexible solution. Crude but can be refined.

这里有一个更灵活的解决方案。原油,但可以提炼。

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

    }
}

#1


65  

Here is how you would add query string parameters using HttpClient 4.2 and later:

下面是如何使用HttpClient 4.2和稍后添加查询字符串参数的方法:

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

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

The resulting URI would look like:

产生的URI如下所示:

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

#2


23  

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

如果希望在创建请求之后添加查询参数,请尝试将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);

#3


10  

The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

HttpParams接口没有用于指定查询字符串参数,而是用于指定HttpClient对象的运行时行为。

If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.

如果你想传递查询字符串参数,你需要自己在URL上组装它们。

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

Remember to encode the values first (using URLEncoder).

记住先对值进行编码(使用URLEncoder)。

#4


3  

I am using httpclient 4.4.

我正在使用httpclient 4.4。

For solr query I used the following way and it worked.

对于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);
}

#5


1  

This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)

这种方法是可行的,但是当你动态地获得params时,有时是1、2、3或更多,就像SOLR搜索查询(例如)

Here is a more flexible solution. Crude but can be refined.

这里有一个更灵活的解决方案。原油,但可以提炼。

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

    }
}