android用okhttp发送带header的get请求(单一url、带参数)
程序员文章站
2024-02-18 18:17:22
...
//发送get请求,单一url
public static Map<String, Object> sendGet_url(String url, Map<String, String> map_header) throws IOException {
//添加header信息
Headers.Builder builder_header = new Headers.Builder();
for (String key : map_header.keySet()) {
builder_header.add(key, Objects.requireNonNull(map_header.get(key)));
}
Headers headers = builder_header.build();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).headers(headers).build();
LocalTime startTime = LocalTime.now();//响应开始时间
Response response = client.newCall(request).execute();
LocalTime endTime = LocalTime.now();//响应结束时间
int code = response.code();
if (code != 200) {
Log.e(cn.uiautomator.Constants.TAG, url + "\n" + response);
}
Map<String, Object> map = new HashMap<>();
map.put("code", code);
map.put("entity", Objects.requireNonNull(response.body()).string());
map.put("responseTime", Duration.between(startTime, endTime).toMillis());
response.close();
return map;
}
//发送get请求,带参数
public static Map<String, Object> sendGet_body(String url, Map<String, String> map_header, Map<String, String> map_body) throws IOException {
//添加header
Headers.Builder builder_header = new Headers.Builder();
for (String key : map_header.keySet()) {
builder_header.add(key, Objects.requireNonNull(map_header.get(key)));
}
Headers headers = builder_header.build();
//添加body
HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
for (String key : map_body.keySet()) {
urlBuilder.addQueryParameter(key, map_body.get(key));
}
//发送请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(urlBuilder.build()).headers(headers).build();
LocalTime startTime = LocalTime.now();//响应开始时间
Response response = client.newCall(request).execute();
LocalTime endTime = LocalTime.now();//响应结束时间
int code = response.code();
if (code != 200) {
Log.e(cn.uiautomator.Constants.TAG, url + "\n" + response);
}
Map<String, Object> map = new HashMap<>();
map.put("code", code);
map.put("entity", Objects.requireNonNull(response.body()).string());
map.put("responseTime", Duration.between(startTime, endTime).toMillis());
response.close();
return map;
}
上一篇: JAVA面向对象进阶