android 封装post请求,包含header data cookie file,并简单调用
时间: 2024-03-16 22:42:49 浏览: 95
好的,以下是一个封装了POST请求的示例代码,它包含了header、data、cookie和file的参数,并且提供了简单的调用方法:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpUtil {
private static String boundary = "---------------------------" + System.currentTimeMillis();
private static String CRLF = "\r\n";
/**
* 发送POST请求
*
* @param urlStr 请求地址
* @param headers 请求头部参数
* @param params 请求参数
* @param cookies 请求cookie
* @param files 请求文件
* @return 返回响应结果
*/
public static String sendPostRequest(String urlStr, Map<String, String> headers, Map<String, String> params, Map<String, String> cookies, Map<String, File> files) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 设置请求头部参数
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 设置请求cookie
if (cookies != null && !cookies.isEmpty()) {
StringBuilder sbCookie = new StringBuilder();
for (Map.Entry<String, String> entry : cookies.entrySet()) {
sbCookie.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
}
conn.setRequestProperty("Cookie", sbCookie.toString());
}
dos = new DataOutputStream(conn.getOutputStream());
// 设置请求参数
if (params != null && !params.isEmpty()) {
StringBuilder sbParams = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sbParams.append("--").append(boundary).append(CRLF);
sbParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(CRLF);
sbParams.append(CRLF);
sbParams.append(entry.getValue()).append(CRLF);
}
dos.write(sbParams.toString().getBytes());
}
// 设置请求文件
if (files != null && !files.isEmpty()) {
for (Map.Entry<String, File> entry : files.entrySet()) {
File file = entry.getValue();
if (!file.exists()) {
continue;
}
// 文件参数头部
StringBuilder sbFile = new StringBuilder();
sbFile.append("--").append(boundary).append(CRLF);
sbFile.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"; filename=\"").append(file.getName()).append("\"").append(CRLF);
sbFile.append("Content-Type: application/octet-stream").append(CRLF);
sbFile.append(CRLF);
dos.write(sbFile.toString().getBytes());
// 文件内容
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
dos.write(buffer, 0, len);
}
dos.write(CRLF.getBytes());
}
}
// 请求结束标志
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
dos.write(endData);
// 响应结果
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sbResponse = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sbResponse.append(line);
}
return sbResponse.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
if (fis != null) {
fis.close();
}
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
```
使用示例:
```java
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0");
headers.put("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
Map<String, String> params = new HashMap<>();
params.put("name", "John");
params.put("age", "18");
Map<String, String> cookies = new HashMap<>();
cookies.put("session_id", "xxxxxxxxxxxx");
Map<String, File> files = new HashMap<>();
files.put("image", new File("image.png"));
String response = HttpUtil.sendPostRequest("http://localhost:8080/api", headers, params, cookies, files);
System.out.println(response);
```
以上代码中,首先根据传入的参数构建了一个HTTP连接,并设置了请求的方法为POST。然后根据传入的headers、params、cookies和files参数分别设置了请求头部参数、请求参数、请求cookie和请求文件。最后向服务器发送请求,并读取响应结果返回。
阅读全文