安卓怎么post数据 包括header和body
时间: 2024-06-10 17:06:15 浏览: 106
您可以使用以下代码片段将数据作为HTTP POST请求发送:
```java
String url = "http://example.com/post";
String requestBody = "data1=value1&data2=value2";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// 设置请求头部
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 发送请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(requestBody);
wr.flush();
wr.close();
// 获取响应
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
```
其中,`requestBody` 是您要发送的数据,可按照以下格式进行设置:
```
data1=value1&data2=value2
```
如果您需要设置请求头部,可以使用 `setRequestProperty(String key, String value)` 方法设置,例如:
```
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
```
阅读全文