>我现在有一个问题,发生的事情是我有一个带有代码点火器的 api 休息,我发出 post 请求,它返回一个我需要用来在我的应用程序中显示的 json。我使用RestTemplate
但我无法得到答案来显示它。感谢您的帮助。
邮递员的回应是:
{"response": "iiprak"}
和我的应用代码:
public String generate(Coupon coupon){
try {
Map<String, Integer> values = new HashMap<String, Integer>();
values.put("id_client", coupon.getId_client());
values.put("id_promo", coupon.getId_promo());
JSONObject jsonObject = new JSONObject(values);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toString(), headers);
//restTemplate.postForEntity(BASE_URL, entity, null);
ResponseEntity<String> response = restTemplate.postForEntity(BASE_URL, entity, null);
String coupon = response.getBody();
return coupon;
} catch (Exception e){
return null;
}
}
您似乎正在从 UI 线程调用restTemplate.postForEntity()
。无法从 UI 线程进行网络调用。在您的情况下,它将引发异常并发生return null
。
尝试在AsyncTask
或Thread
中拨打电话,并带有Handler
。
这里有一个使用 Spring 框架和AsyncTask
的很好的例子 - https://spring.io/guides/gs/consuming-rest-android/。
上面页面中的示例包含您的要求:
private class HttpRequestTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
try {
// BELOW IS YOUR CODE IN QUESTION, I am not validating it.
Map<String, Integer> values = new HashMap<String, Integer>();
values.put("id_client", coupon.getId_client());
values.put("id_promo", coupon.getId_promo());
JSONObject jsonObject = new JSONObject(values);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toString(), headers);
//restTemplate.postForEntity(BASE_URL, entity, null);
ResponseEntity<String> response = restTemplate.postForEntity(BASE_URL, entity, null);
String coupon = response.getBody();
return coupon;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
@Override
protected void onPostExecute(String coupon) {
couponTextView.setText("Coupon is: " + coupon);
}
}
现在您可以像这样执行任务:
new HttpRequestTask().execute();