我创建了一个 API 控制器来仅处理来自 Android 应用程序的 json 请求。当然,我正在使用令牌身份验证。更好的是:使用 POST 发送请求:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.170:3000/api/get_all");
httppost.setHeader("content-type", "application/json; charset= utf-8");
httppost.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("token", token);
StringEntity entity = new StringEntity(json.toString(), "utf-8");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
或获取:
httpget = new HttpGet("http://10.0.0.170:3000/api/get_all?"+"token="+token);
httpget.setHeader("content-type", "application/json; charset= utf-8");
httpget.setHeader("Accept", "application/json");
response = httpclient.execute(httpget);
result = EntityUtils.toString(response.getEntity());
显然 GET 中的代码更少,但是还有其他一些理由更喜欢其中一个吗?