【发布时间】: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