我试图在java中提出一个POST请求,但这并不像预期的那样有效。
在this post之后,下面是我目前拥有的代码
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, Consts.UTF_8);我无法理解的是,在调试此data时,调试器显示的值为
Content=text/json,Authorization=Bearer bZXL7hwy5vo7YnbiiGogKy6WTyCmioi8
这是完全可以预料的,在我完全不知所措的地方,在这个电话之后,实体的价值是,
内容-类型:application/x form-urlencoded;charset=UTF-8,内容长度: 78,分块: false
这个调用除了忽略我传递给它的数据之外,什么也没做。
我在这里做错了什么?
编辑
更多代码
打电话者
String authURL = "https://api.ecobee.com/1/thermostat";
authURL += "?format=json&body=" + getSelection();
// request headers
ArrayList<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("Content-Type", "text/json"));
nvps.add(new BasicNameValuePair("Authorization", "Bearer " + code));
// make the api call
String apiResponse = HttpUtils.makeRequest(RequestMethod.POST, authURL, nvps);makeRequest法
public static String makeRequest(RequestMethod method, String url, ArrayList<BasicNameValuePair> data) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpRequestBase request = null;
switch (method) {
case POST:
// new post request
request = new HttpPost(url);
// encode the post data
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, Consts.UTF_8); // <-- this is where I have the issue
((HttpPost) request).setEntity(entity);
break;
...发布于 2016-07-03 18:06:40
如前所述,它不能工作的原因是头应该直接设置在请求中,而不是实体中。
因此,您可以使用如下所示:
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, Consts.UTF_8);
request.setHeader("Content-type", "application/json");
request.setHeader("Authorization","Bearer bZXL7hwy5vo7YnbiiGogKy6WTyCmioi8");
request.setEntity(entity);发布于 2016-07-03 17:27:35
内容-类型/授权是标题,因此应该按照注释中的建议使用setHeader()传递。
更新:内容类型应该是application/json,而不是text/json。
与UrlEncodedFormEntity/BasicNameValuePair不同,您应该使用StringEntity并在那里传递getSelection()的结果。
https://stackoverflow.com/questions/38172111
复制相似问题