android 封装get请求,包含header data cookie file,并简单调用
时间: 2024-04-07 13:28:46 浏览: 64
好的,下面是一个简单的封装了 header、data、cookie 和 file 的 GET 请求的示例代码:
```java
public class HttpUtil {
private static final String CHARSET_UTF8 = "UTF-8";
public static void sendGetRequest(String url, Map<String, String> headers,
Map<String, String> params, Map<String, File> files, String cookie,
final Callback callback) {
// 创建请求参数字符串
StringBuilder paramBuilder = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
paramBuilder.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), CHARSET_UTF8)).append("&");
}
paramBuilder.deleteCharAt(paramBuilder.length() - 1);
}
String paramString = paramBuilder.toString();
// 创建请求 URL
if (!TextUtils.isEmpty(paramString)) {
if (!url.endsWith("?")) {
url += "?";
}
url += paramString;
}
// 创建请求对象
HttpGet request = new HttpGet(url);
// 添加请求头
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
// 添加 Cookie
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("Cookie", cookie);
}
// 创建请求体
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName(CHARSET_UTF8));
// 添加文件
if (files != null && !files.isEmpty()) {
for (Map.Entry<String, File> entry : files.entrySet()) {
builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
}
}
// 设置请求体
request.setEntity(builder.build());
// 发送请求
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
HttpResponse response = new DefaultHttpClient().execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (callback != null) {
callback.onResponse(result);
}
}
}.execute();
}
public interface Callback {
void onResponse(String result);
}
}
```
使用示例:
```java
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
Map<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
Map<String, File> files = new HashMap<>();
files.put("file1", new File("path/to/file1"));
files.put("file2", new File("path/to/file2"));
String cookie = "name=value; name2=value2";
HttpUtil.sendGetRequest("http://www.example.com", headers, params, files, cookie, new HttpUtil.Callback() {
@Override
public void onResponse(String result) {
// 处理响应结果
}
});
```
阅读全文