如何用Android发送POST请求并携带数据传输
时间: 2023-03-29 09:03:44 浏览: 75
您可以使用 Android 中的 HttpURLConnection 类来发送 POST 请求并携带数据传输。以下是一个简单的示例代码:
```
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置请求头
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 设置请求体
JSONObject jsonParam = new JSONObject();
jsonParam.put("key1", "value1");
jsonParam.put("key2", "value2");
OutputStream os = conn.getOutputStream();
os.write(jsonParam.toString().getBytes("UTF-8"));
os.flush();
os.close();
// 获取响应
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
is.close();
String result = response.toString();
// 处理响应结果
} else {
// 处理错误情况
}
conn.disconnect();
```
请注意,您需要将请求体中的数据转换为 JSON 格式,并设置请求头的 Content-Type 为 application/json;charset=UTF-8。另外,您还需要处理响应结果和错误情况。