【问题标题】:What does UrlEncodedFormEntity do in Apache HttpClient 4?UrlEncodedFormEntity 在 Apache HttpClient 4 中做了什么?
【发布时间】:2019-10-21 07:08:37
【问题描述】:

如果您想使用参数进行 HTTP Post 并以“x-www-form-urlencoded”的内容类型发送它,那么在 Apache HTTP Client 3 中执行此操作的方法是...

    HttpMethod method = new PostMethod(myUrl)

    method.setParams(mp)
    method.addParameter("user_name", username)
    method.addParameter("password", password)

    method.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')

    int responseCode = httpClient.executeMethod(method)

但是 Apache HTTP Client 4 引入了 UrlEncodedFormEntity 对象,所以新的做法是......

HttpPost post = new HttpPost(url);

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user_name", username));
urlParameters.add(new BasicNameValuePair("password", password));;

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);

这个 UrlEncodedFormEntity 对象除了将内容类型设置为“x-www-form-urlencoded”之外还有什么用途?

docs 说它创建了一个“由 url 编码对列表组成的实体”,但这不能仅通过设置内容类型来完成吗?

【问题讨论】:

标签: java http-post apache-httpclient-4.x urlencode


【解决方案1】:

HttpEntity 接口是控制如何处理请求/响应主体的顶级接口。在这种情况下,您使用的是 UrlEncodedFormEntity,它知道如何对参数进行编码并以所需的格式输出它们。

【讨论】:

  • 所以 UrlEncodedFormEntity 将对我提供给它的 BasicNameValuePair 的键和值进行 Url 编码?
猜你喜欢
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2011-10-15
  • 2021-11-06
  • 1970-01-01
  • 2015-03-21
相关资源
最近更新 更多