我尝试使HTTPGET上服务器的请求。 但在消息体应该是一个JSON对象。 下面的代码是不工作,因为UNIT_ID和sercret_key没有在身体上的消息服务器发送。 我该怎么做?
的JSONObject:
{
"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这个请求时这样
$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);
Answer 1:
基本上,你不能与HTTP发送体内(JSON或任何东西)行数据/ GET请求。 该协议根本不容许你这样做。 很明显,你将不得不使用POST做,在Android的太多。 :)
UPDATE
我是不正确的。 逸岸的协议确实让你把一个实体到请求对象。 这个类可以用来代替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发现这里
Answer 2:
如果您wnat以JSON对象添加到您的请求时,它必须是一个POST请求,这是你如何执行它:
public static String sendComment (String commentString, int taskId, String sessionId, int displayType, String url) throws Exception{
//creating map object to creat Json object from it
Map jsonValues = new HashMap();
jsonValues.put("sessionID", sessionId);
jsonValues.put("NewTaskComment", commentString);
jsonValues.put("TaskID" , taskId);
jsonValues.put("DisplayType" , displayType);
JSONObject json = new JSONObject(jsonValues);
//creating a post request.
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url + SEND_COMMENT_ACTION);
//setting json object to post request.
AbstractHttpEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity);
//this is your response:
HttpResponse response = client.execute(post);
return getContent(response);
}
Answer 3:
这是很好的例子如何做到这一点,这是工作。
Apache的HttpClient的GET与身体
但是,这种方法是针对RESTful的API,我认为。
文章来源: HttpGet with request body android