【发布时间】:2014-05-03 16:15:13
【问题描述】:
我有以下代码用于在 Android 中使用 DefaultHttpClient 的 http 请求,我注意到处理 POST 和 GET 请求之间的区别。比如 POST 请求,首先直接将 URL 传递给 HttpPost,然后进行编码。但是,对于 GET 请求,首先进行编码,然后传递带参数的 url。这是必须遵循的某种规则,还是我可以为 POST 和 GET 执行类似的编码和 url 传递序列?提前致谢。
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
//encode the post data
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
【问题讨论】:
标签: android http http-post http-get