如果您希望使用参数执行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 client4引入了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编码对列表组成的实体”,但这不能仅仅通过设置内容类型来实现吗?
发布于 2019-06-06 02:33:48
HttpEntity接口是控制如何处理请求/响应主体的顶级接口。在本例中,您使用的UrlEncodedFormEntity知道如何对参数进行编码并以所需的格式输出它们。
https://stackoverflow.com/questions/56466139
复制相似问题