我正在使用 HttpUrlConnection 与服务器通信。
InputStream is = null;
String parammetrs = "clientId=" + client.getId() + "&bikeId=" + 1;
BufferedReader br = null;
String json = null;
try {
URL url = new URL(myURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
connection.getOutputStream().write(parammetrs.getBytes("UTF-8"));
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
json = (br.readLine().toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
OnPostExecute 对我来说仍然是空的。如何从服务器获取布尔响应、错误 (402, ...)?
json表单中的答案示例{ "response": true }有一个非常有用的库
OkHttp:http ://square.github.io/okhttp/这大大简化了网络请求的工作。例如,在您的情况下,它看起来像这样: