OKHTTP在PUT请求中发送空值

时间:2017-08-26 19:55:37

标签: android okhttp3

我是Android开发的新手,我只是学习通过OKHTTP发送http请求我成功获得了GET和POST方法的结果,但我能够正确发送PUT请求。

这是我的代码,请看一下。

public void btn_reset_click_handler(View view) {
    if (NetworkHelper.hasConnectivity(this)){

        showProgress(true);

        RequestPackage requestPackage = new RequestPackage();
        requestPackage.setEndPoint("reset_password");
        requestPackage.setMethod("PUT");
        requestPackage.setParam("email", username);
        requestPackage.setParam("new_password", password);

        String response = download(requestPackage);

    }else{
        Helper.displayToast(this, "Make Sure you have active network connection!");
    }

}

public static String download(RequestPackage requestPackage) throws IOException {

    String address = requestPackage.getEndpoint();

    OkHttpClient client = new OkHttpClient();

    Request.Builder requestBuilder = new Request.Builder().url(address);

    if (requestPackage.getMethod().equals("POST") || requestPackage.getMethod().equals("PUT")) {

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        Map<String, String> params = requestPackage.getParams();

        for (String key : params.keySet()) {
            builder.addFormDataPart(key, params.get(key));
        }
        RequestBody requestBody = builder.build();
        requestBuilder.method(requestPackage.getMethod(), requestBody);

    }

    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();

    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Exception: Response code " + response.code());
    }
}

0 个答案:

没有答案