How to use OKHTTP to make a post request?

后端 未结 13 1063
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 05:06

I read some examples which are posting jsons to the server.

some one says :

OkHttp is an implementation of the HttpUrlConnection interface p

相关标签:
13条回答
  • 2020-12-02 05:27

    Here is my method to do post request first pass in method map and data like

    HashMap<String, String> param = new HashMap<String, String>();
    
    param.put("Name", name);
    param.put("Email", email);
    param.put("Password", password);
    param.put("Img_Name", "");
    
    final JSONObject result = doPostRequest(map,Url);
    
    public static JSONObject doPostRequest(HashMap<String, String> data, String url) {
    
        try {
            RequestBody requestBody;
            MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    
            if (data != null) {
    
    
                for (String key : data.keySet()) {
                    String value = data.get(key);
                    Utility.printLog("Key Values", key + "-----------------" + value);
    
                    mBuilder.addFormDataPart(key, value);
    
                }
            } else {
                mBuilder.addFormDataPart("temp", "temp");
            }
            requestBody = mBuilder.build();
    
    
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
    
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            Utility.printLog("URL", url);
            Utility.printLog("Response", responseBody);
            return new JSONObject(responseBody);
    
        } catch (UnknownHostException | UnsupportedEncodingException e) {
    
            JSONObject jsonObject=new JSONObject();
    
            try {
                jsonObject.put("status","false");
                jsonObject.put("message",e.getLocalizedMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.e(TAG, "Error: " + e.getLocalizedMessage());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject=new JSONObject();
    
            try {
                jsonObject.put("status","false");
                jsonObject.put("message",e.getLocalizedMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
        }
        return null;
    }
    

    0 讨论(0)
  • 2020-12-02 05:29

    This is one of the possible solutions to implementing an OKHTTP post request without a request body.

    RequestBody reqbody = RequestBody.create(null, new byte[0]);  
    Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0");
    clientOk.newCall(formBody.build()).enqueue(OkHttpCallBack());
    
    0 讨论(0)
  • 2020-12-02 05:30

    You can make it like this:

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}");
    
        OkHttpClient client = new OkHttpClient();
    
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part
                .build();
    
        Call call = client.newCall(request);
    
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
    
                Log.e("HttpService", "onFailure() Request was: " + request);
    
                e.printStackTrace();
            }
    
            @Override
            public void onResponse(Response r) throws IOException {
    
                response = r.body().string();
    
                Log.e("response ", "onResponse(): " + response );
    
            }
        });
    
    0 讨论(0)
  • 2020-12-02 05:32

    OkHttp POST request with token in header

           RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("search", "a")
                .addFormDataPart("model", "1")
                .addFormDataPart("in", "1")
                .addFormDataPart("id", "1")
                .build();
        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url("https://somedomain.com/api")
                .post(requestBody)
                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIkMnkkMTAkZzZrLkwySlFCZlBmN1RTb3g3bmNpTzltcVwvemRVN2JtVC42SXN0SFZtbzZHNlFNSkZRWWRlIiwic3ViIjo0NSwiaWF0IjoxNTUwODk4NDc0LCJleHAiOjE1NTM0OTA0NzR9.tefIaPzefLftE7q0yKI8O87XXATwowEUk_XkAOOQzfw")
                .addHeader("cache-control", "no-cache")
                .addHeader("Postman-Token", "7e231ef9-5236-40d1-a28f-e5986f936877")
                .build();
    
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
    
            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String myResponse = response.body().string();
    
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("response", myResponse);
                            progress.hide();
                        }
                    });
                }
            }
        });
    
    0 讨论(0)
  • 2020-12-02 05:32
    1. Add the following to the build.gradle

    compile 'com.squareup.okhttp3:okhttp:3.7.0'

    1. Create a new thread, in the new thread add the following code.
    OkHttpClient client = new OkHttpClient();
    MediaType MIMEType= MediaType.parse("application/json; charset=utf-8");
    RequestBody requestBody = RequestBody.create (MIMEType,"{}");
    Request request = new Request.Builder().url(url).post(requestBody).build();
    Response response = client.newCall(request).execute();
    
    0 讨论(0)
  • 2020-12-02 05:36
       protected Void doInBackground(String... movieIds) {
                    for (; count <= 1; count++) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                    Resources res = getResources();
                    String web_link = res.getString(R.string.website);
    
                    OkHttpClient client = new OkHttpClient();
    
                    RequestBody formBody = new FormBody.Builder()
                            .add("name", name)
                            .add("bsname", bsname)
                            .add("email", email)
                            .add("phone", phone)
                            .add("whatsapp", wapp)
                            .add("location", location)
                            .add("country", country)
                            .add("state", state)
                            .add("city", city)
                            .add("zip", zip)
                            .add("fb", fb)
                            .add("tw", tw)
                            .add("in", in)
                            .add("age", age)
                            .add("gender", gender)
                            .add("image", encodeimg)
                            .add("uid", user_id)
                            .build();
                    Request request = new Request.Builder()
                            .url(web_link+"edit_profile.php")
                            .post(formBody)
                            .build();
    
                    try {
                        Response response = client.newCall(request).execute();
    
                        JSONArray array = new JSONArray(response.body().string());
                        JSONObject object = array.getJSONObject(0);
    
                        hashMap.put("msg",object.getString("msgtype"));
                        hashMap.put("msg",object.getString("msg"));
                        // Do something with the response.
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
    
    
                    return null;
                }
    
    0 讨论(0)
提交回复
热议问题