安卓如何post一个json并接收返回信息
时间: 2024-05-01 08:17:08 浏览: 83
Android向Java后台发送请求并返回Json数据
4星 · 用户满意度95%
安卓可以使用HttpURLConnection或者OkHttp库来发送POST请求并接收返回信息。
使用HttpURLConnection:
```java
public void postData(String url, JSONObject jsonObj) {
try {
URL endpoint = new URL(url);
HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(jsonObj.toString().getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String result = response.toString();
// 处理返回结果
} else {
// 处理错误情况
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
```
使用OkHttp:
```java
public void postData(String url, JSONObject jsonObj) {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObj.toString());
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
// 处理返回结果
} else {
// 处理错误情况
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
阅读全文