1. 程式人生 > >OkHttp使用post請求注意點

OkHttp使用post請求注意點

簡單談談個人在使用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))); } } return builder.build();