我尝试通过 HttpGet 在服务器上发出请求。但在消息正文中应该是一个 json 对象。下面的代码不起作用,因为 unit_id 和 sercret_key 没有在正文消息中发送到服务器。我该怎么做?
JSON对象:
{
"unit_id": 12345,
"secret_key": "sdfadfsa6as987654754"
}
我的代码:
private HttpResponse makeRequest(int id, String secretKey) throws Exception {
BasicHttpParams params = new BasicHttpParams();
params.setParameter("id", id);
params.setParameter("secret_key", secretKey);
httpget.setHeader("Accept", "application/json");
httpget.setParams(params);
httpget.setHeader("Content-type", "application/json");
// Handles what is returned from the page
return httpclient.execute(httpget);
}
编辑:在 php 中这个请求是这样发出的
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://0101.apiary.io/api/reservations/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"unit_id\": 12345,\n \"secret_key\": \"sdfadfsa6as987654754\"\n}");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
最佳答案
基本上,您不能使用 HTTP/GET 请求在正文(JSON 或任何内容)中发送行数据。 协议(protocol)根本不允许您这样做。显然,您也必须使用 POST 在 Android 中执行此操作。 :)
更新
我错了。事实上,该协议(protocol)确实允许您将一个实体放入请求对象中。可以使用此类代替 Apache HttpGet
。
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(URI uri) {
super();
setURI(uri);
}
public HttpGetWithEntity(String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return HttpGet.METHOD_NAME;
}
}
然后像下面这样使用它,
HttpClient client = new DefaultHttpClient();
HttpGetWithEntity myGet = new HttpGetWithEntity("Url here");
myGet.setEntity(new StringEntity("This is the body", "UTF8"));
HttpResponse response = client.execute(myGet);
找到HttpGetWithEntity
的源here
关于java - HttpGet 与请求正文 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15202300/