如何使用查询参数发送http POST

时间:2016-04-14 10:11:16

标签: java http post query-string

我想通过我的java客户端发送http POST。

有没有办法在POST正文中发送查询参数和内容?

这是我的java http客户端:

@Override
public ResponseOrError sendPost(String url, String bodyContent) {
    url = urlUtils.getHttpUrl(url);

    ResponseOrError responseOrError = new ResponseOrError();
    final RetryListenerWithBooleanFlags listener = new RetryListenerWithBooleanFlags();
    try {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        Callable<ResponseOrError> callable = getCallable(httpPost);
        retryer = getRetryer(listener);
        responseOrError = retryer.call(callable);
        fillResponseOrError(responseOrError, listener);

    } catch (Exception e) {
        responseOrError.error = new Error();
        String errorMsg = getStatusCode(responseOrError, listener);
        responseOrError.error.errorMsg = e.getMessage() + errorMsg;
    }
    return responseOrError;
}

3 个答案:

答案 0 :(得分:0)

请务必检查Java API。

这应该有用。

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key", "value"));
post.setEntity(new UrlEncodedFormEntity(params));

答案 1 :(得分:0)

是否有理由使用org.apache.http.client中的HttpPost?

不幸的是我不熟悉那个库/类,但是如果没有特别的理由使用这个库,那么选择就是简单地使用HttpURLConnection

示例(手头没有编译器,因此可能会有一些错误):

URL url = new URL("http://..");
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setRequestMethod("POST"); //it's a post request
httpCon.setDoInput(true); //read response
httpCon.setDoOutput(true); //send Post body
... = httpCon.getOutputStream(); //Here you go, do whatever you want with this stream

答案 2 :(得分:0)

只需将参数附加到网址即可:

url = url + "?param=value&otherparam=othervalue";

确保使用:

  • ?:启动查询字符串
  • =:将参数与其值
  • 相关联
  • &:分隔参数/值对

例如,如果参数值包含空格,则需要对参数值进行编码。

为此,请使用URLEncoder类:

String encoded = URLEncoder.encode(value, StandardCharsets.UTF_8);

有了这个,some value with blank spaces将成为some%20value%20with%20blank%20spaces

相关问题