How to use OKHTTP to make a post request?

后端 未结 13 1066
佛祖请我去吃肉
佛祖请我去吃肉 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:39

    To add okhttp as a dependency do as follows

    • right click on the app on android studio open "module settings"
    • "dependencies"-> "add library dependency" -> "com.squareup.okhttp3:okhttp:3.10.0" -> add -> ok..

    now you have okhttp as a dependency

    Now design a interface as below so we can have the callback to our activity once the network response received.

    public interface NetworkCallback {
    
        public void getResponse(String res);
    }
    

    I create a class named NetworkTask so i can use this class to handle all the network requests

        public class NetworkTask extends AsyncTask{
    
        public NetworkCallback instance;
        public String url ;
        public String json;
        public int task ;
        OkHttpClient client = new OkHttpClient();
        public static final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");
    
        public NetworkTask(){
    
        }
    
        public NetworkTask(NetworkCallback ins, String url, String json, int task){
            this.instance = ins;
            this.url = url;
            this.json = json;
            this.task = task;
        }
    
    
        public String doGetRequest() throws IOException {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
    
            Response response = client.newCall(request).execute();
            return response.body().string();
        }
    
        public String doPostRequest() throws IOException {
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }
    
        @Override
        protected String doInBackground(String[] params) {
            try {
                String response = "";
                switch(task){
                    case 1 :
                        response = doGetRequest();
                        break;
                    case 2:
                        response = doPostRequest();
                        break;
    
                }
                return response;
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            instance.getResponse(s);
        }
    }
    

    now let me show how to get the callback to an activity

        public class MainActivity extends AppCompatActivity implements NetworkCallback{
        String postUrl = "http://your-post-url-goes-here";
        String getUrl = "http://your-get-url-goes-here";
        Button doGetRq;
        Button doPostRq;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button button = findViewById(R.id.button);
    
            doGetRq = findViewById(R.id.button2);
        doPostRq = findViewById(R.id.button1);
    
            doPostRq.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MainActivity.this.sendPostRq();
                }
            });
    
            doGetRq.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MainActivity.this.sendGetRq();
                }
            });
        }
    
        public void sendPostRq(){
            JSONObject jo = new JSONObject();
            try {
                jo.put("email", "yourmail");
                jo.put("password","password");
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
        // 2 because post rq is for the case 2
            NetworkTask t = new NetworkTask(this, postUrl,  jo.toString(), 2);
            t.execute(postUrl);
        }
    
        public void sendGetRq(){
    
        // 1 because get rq is for the case 1
            NetworkTask t = new NetworkTask(this, getUrl,  jo.toString(), 1);
            t.execute(getUrl);
        }
    
        @Override
        public void getResponse(String res) {
        // here is the response from NetworkTask class
        System.out.println(res)
        }
    }
    

提交回复
热议问题