安卓如何post请求发送一个json
时间: 2024-05-10 12:20:34 浏览: 77
可以使用HttpURLConnection或者OkHttp库来发送POST请求,并且将JSON作为请求体发送。
下面是用HttpURLConnection发送POST请求并发送JSON的代码示例:
```
try {
// 创建URL对象
URL url = new URL("http://example.com/api/users");
// 创建HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// 创建JSON对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John Doe");
jsonObject.put("age", 30);
// 将JSON转换为字符串
String jsonInputString = jsonObject.toString();
// 将JSON字符串写入请求体
OutputStream os = conn.getOutputStream();
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
// 发送请求
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("POST request failed: " + responseCode);
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
```
如果使用OkHttp库,可以使用以下代码:
```
try {
// 创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
// 创建JSON对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John Doe");
jsonObject.put("age", 30);
// 创建RequestBody对象
RequestBody body = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
// 创建Request对象
Request request = new Request.Builder()
.url("http://example.com/api/users")
.post(body)
.build();
// 发送请求
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
// 读取响应
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("POST request failed: " + response.code());
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
```
阅读全文