开发中遇到了需要基于okhttp3实现网络请求的需求,第一次用到这个,网上对okhttp的post请求的实现过程不太全面,现以json格式的requestBody为例整理一个完整的post请求
public Response doPostByParams(String uri, Map parameters) {
Response response = null;
String newUrl = sonarServerUrl + uri;
Map<String, String> httpHeaders = getHeader();
FormBody.Builder builder = new FormBody.Builder();
for (String key : parameters.keySet()) {
builder.add(key, parameters.get(key));
}
RequestBody formBody = builder.build();
Request okRequest = (new Request.Builder())
.headers(HttpClientHelper.createHeaders(HttpMediaTypeConstant.MEDIA_TYPE_JSON, httpHeaders))
.url(newUrl).post(formBody).build();
try {
response = okHttpClient.newCall(okRequest).execute();
} catch (IOException ioException) {
throw new CjjServerException(500, "Sonar Api 请求错误", ioException);
} finally {
IOUtils.closeQuietly(response);
}
return response;
}
以上是基于okhttp3的post的主体方法,其中requestBody构建的主体基于这样一个循环构建:
FormBody.Builder builder = new FormBody.Builder();
for (String key : parameters.keySet()) {
builder.add(key, parameters.get(key));
}
附周边其他方法:
1.get request header
private Map<String, String> getHeader() {
try {
Map<String, String> httpHeaders = new HashMap<>();
httpHeaders.put("Authorization",
"Basic " + Base64Utils.encodeToString((sonarServerToken + ":").getBytes("US-ASCII")));
return httpHeaders;
} catch (Exception e) {
throw new CjjServerException(500, "Sonar token 设置Header错误", e);
}
}
2.
|