如果您要使用参数进行HTTP发布,并以“ 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);
除了将内容类型设置为“ x-www-form-urlencoded”之外,此UrlEncodedFormEntity对象还用于什么目的?
docs说它创建了一个“由一系列url编码对组成的实体”,但是不能仅通过设置内容类型来做到这一点吗?
答案 0 :(得分:1)
HttpEntity
接口是控制如何处理请求/响应主体的顶级接口。在这种情况下,您使用的UrlEncodedFormEntity
知道如何对参数进行编码并以所需的格式输出它们。