【问题标题】:how to send http POST with query params如何使用查询参数发送 http POST
【发布时间】:2016-04-14 10:11:15
【问题描述】:

我想通过我的 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;
}

【问题讨论】:

标签: java http post query-string


【解决方案1】:

一定要检查 Java API。

这应该可行。

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

【讨论】:

  • 在某些情况下,这不起作用。 (即安全环境..)
【解决方案2】:

是否有理由使用来自 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

【讨论】:

  • 为什么我应该更喜欢 HttpURLConnection 而不是 org.apache.http.client
  • @user1065869 可能是品味/要求/维护。 org.apache.http.client 似乎是第三方库,而 HttpURLConnection 应该是直接可用的。添加第三方库意味着您应该有一个好的计划来监控它的更新(安全版本)并应用这些补丁(除了它通常会增加攻击面)。对于HttpURLConnection,您只需运行最新的jre(无论如何您都应该这样做)。所以我个人的口味主要是远离第三方库。
  • 但这取决于库的功能、维护的好坏以及我需要多少功能以及任务的复杂程度。对于一个简单的 POST 请求,我个人会使用HttpURLConnection。但是,如果图书馆能提供很多我真正需要的东西,我可能会在积极维护的情况下使用它,并且它背后的 ppl 知道他们在做什么(从安全角度来看)
【解决方案3】:

只需将参数附加到 URL,就这么简单:

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

确保您使用:

  • ?: 开始查询字符串
  • =:将参数与其值关联起来
  • &amp;:分离参数/值对

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

为此,请使用URLEncoder 类:

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

这样,some value with blank spaces 将变为 some%20value%20with%20blank%20spaces

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2019-12-09
    • 2013-01-11
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多