commons httpclient-将查询字符串参数添加到GET / POST请求


78

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

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

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

它返回null。实际上parameterMap是完全空的。当我在创建HttpGet请求之前手动将参数附加到url时,该参数在servlet中可用。当我使用附加了queryString的URL从浏览器中访问servlet时也是如此。

这是什么错误?在httpclient 3.x中,GetMethod具有setQueryString()方法来追加查询字符串。4.x中的等效项是什么?

Answers:


134

这是使用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

32

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

12

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

如果要传递查询字符串参数,则需要自己在URL上组合它们,例如

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

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


3
在创建请求对象之后,是否无法添加查询字符串参数?如果不是,是否有另一种标准方法可以将参数传递给Servlet的任何请求方法(GET / PUT / POST)?
Oceanic 2012年

5

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

此答案将受益于更多的解释
D. Ben Knoble

这个答案对我的情况非常有用,因为我找不到用完整的URI初始化URIBuilder的方法,例如example http://myserver/apipath。初始化时,URIBuilder仅使用http://myserver和忽略/apipath。URI是外部提供的,因此我不想仅使用URIBuilder来手动解析它。
nuoritoveri

2

这种方法是可行的,但不适用于动态获取参数(有时为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

    }
}

GetMethod?是来自httpclient吗?因为问题就是这个。
Walfrat

是的,来自org.apache.commons.httpclient.methods。
拉胡尔·赛尼

啊,是的,但似乎是针对3.x版本的,在4.x版本中,现在是org.apache.http.client.methods.HttpGet
Walfrat

0

这就是我实现URL构建器的方式。我创建了一个Service类来提供URL的参数

public interface ParamsProvider {

    String queryProvider(List<BasicNameValuePair> params);

    String bodyProvider(List<BasicNameValuePair> params);
}

实现方法如下

@Component
public class ParamsProviderImp implements ParamsProvider {
    @Override
    public String queryProvider(List<BasicNameValuePair> params) {
        StringBuilder query = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                query.append("?");
                query.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                query.append("&");
                query.append(basicNameValuePair.toString());
            }
        });
        return query.toString();
    }

    @Override
    public String bodyProvider(List<BasicNameValuePair> params) {
        StringBuilder body = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                body.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                body.append("&");
                body.append(basicNameValuePair.toString());
            }
        });
        return body.toString();
    }
}

当我们需要URL的查询参数时,我只需调用服务并进行构建即可。下面是示例。

Class Mock{
@Autowired
ParamsProvider paramsProvider;
 String url ="http://www.google.lk";
// For the query params price,type
 List<BasicNameValuePair> queryParameters = new ArrayList<>();
 queryParameters.add(new BasicNameValuePair("price", 100));
 queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider

}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.