Android Studio HttpURLConnection 传递 / 发送 JSON 数据
private void request() {
new Thread(new Runnable() {
@Override
public void run() {
try {
String strUrl = "url"; // 你请求的 http 链接
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); // 设置请求方式为 GET
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect(); // 连接
/****************关键***************/
String body = "{\"字段名\":\"内容\"}";
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
/***********************************/
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
InputStream inputStream = connection.getInputStream(); // 得到响应流
JSONObject json = streamToJson(inputStream); // 从响应流中提取 JSON
Log.i("json", json.toString()); // 打印返回的 JSON 观察处理
}
connection.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private JSONObject streamToJson(InputStream inputStream) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
String temp = "";
StringBuilder stringBuilder = new StringBuilder();
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp);
}
JSONObject json = new JSONObject(stringBuilder.toString().trim());
return json;
}