【发布时间】:2020-01-17 09:24:20
【问题描述】:
如果我想从 web api 读取 json,首先我需要 POST 一些 json 到服务器,所以我的代码是:
private class AsyncFetch extends AsyncTask<String, String, String> {
HttpURLConnection conn = null;
InputStream inputStream = null;
StringBuffer out = new StringBuffer();
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://10.54.180.18:8090/TV/api/GetUserInfo");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Authorization", default_token);
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("accountNo", "cb2c2041d9763d84d7d655e81178f444");
jsonObject.put("stationNo", "NURS4");
jsonObject.put("bedNo", "329-1");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
os.flush();
os.close();
//get response
inputStream = conn.getInputStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = inputStream.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn != null) {
conn.disconnect();
}
}
return out.toString();
现在我想查看 repose result(JSON) ,我该怎么做?请帮助我,谢谢。
【问题讨论】:
-
读取 conn.getInputStream() 的回复。
-
os.writeBytes(URLEncoder.encode(jsonObject.toString(), "UTF-8"));` 删除该行。下一行将发送 json。而且你不需要发送两次。
-
Retrofit 是在 Android 上发出请求的行业标准。看看这个code.tutsplus.com/tutorials/…