GET 1、无header
public static String okHttpSendGet(String url) {
try {
Request request = new Request.Builder().url(url).build();
return okHttpSendGet(request);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
2、有header
public static String okHttpSendGet(String url, Map<String, String> header) {
try {
Request.Builder builder = new Request.Builder().url(url);
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = builder.build();
return okHttpSendGet(request);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
POST
public static String sendPost(String url, Map<String, String> header, String param) {
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(mediaType, param);
Request.Builder builder = new Request.Builder()
.url(url)
.post(requestBody);
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = builder.build();
try (Response response = okHttpClient.newCall(request).execute();
ResponseBody responseBody = response.body()) {
if (response.code() == 200) {
if (responseBody == null) {
return null;
} else {
return responseBody.string();
}
} else {
return null;
}
} catch (IOException e) {
log.error("httpUtil错误", e);
}
return null;
}
response解析成JSON
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(responseJson).getAsJsonObject();
response 解析成对象
Gson gson = new GsonBuilder().create();
HttpResponse response = gson.fromJson(httpResult, HttpResponse.class);
|