OkHttp使用post请求注意点

作者: HarryXR | 来源:发表于2016-08-10 16:22 被阅读8445次

简单谈谈个人在使用OkHttp过程中发现的注意点:

1.提交键值对

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
 RequestBody formBody = new FormEncodingBuilder() 
.add("platform", "android") 
.add("name", "bug") 
.add("subject", "XXXXXXXXXXXXXXX")
 .build();  
Request request = new Request.Builder() 
.url(url) 
.post(body)
 .build(); 
 Response response = client.newCall(request).execute(); 
if (response.isSuccessful()) {
 return response.body().string(); 
} 
else { 
throw new IOException("Unexpected code " + response);
 }}```
主要使用FormEncodingBuilder来添加参数值、post url即可
###2.上传文件此处以上传图片为例

protected RequestBody postBody(File file) {
// 设置请求体
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody body = MultipartBody.create(MEDIA_TYPE_PNG, file);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
//这里是 封装上传图片参数
builder.addFormDataPart("file", file.getName(), body);
// 封装请求参数,这里最重要
HashMap<String, String> params = new HashMap<>();
params.put("client","Android"); params.put("uid","1061");
params.put("token","1911173227afe098143caf4d315a436d");
params.put("uuid","A000005566DA77");
//参数以添加header方式将参数封装,否则上传参数为空
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
builder.addPart(Headers.of("Content-Disposition", "form-data; name="" + key + """), RequestBody.create(null, params.get(key))); } }```

相关文章

网友评论

    本文标题:OkHttp使用post请求注意点

    本文链接:https://www.haomeiwen.com/subject/ntdjsttx.html