Android 之OkHttp get 和post

本文介绍如何使用OkHttp库在Android应用中实现GET和POST请求,包括同步与异步方式,并提供了一个完整的示例,展示了从配置依赖到实现请求的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

更新 2017-07-07

第一步

在gradle中配置

dependencies {
 compile 'com.squareup.okhttp3:okhttp:3.8.1'
}
第二步

get,post请求的接口,分别有同步和异步请求

import android.content.Context;
import java.util.Map;
import okhttp3.Callback;
import okhttp3.Response;

public interface NetModuleInterface {

    Response getRequest(Context context, String url);

    void getSyncRequest(Context context, String url, Callback callback);

    Response postReques(Context context, String url, Map<String, String> map);

    void postSyncReques(Context context, String url, Map<String, String> map, Callback callback);

}
第三步 实现接口
import android.content.Context;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NetOkhttpRequest implements NetModuleInterface {

    private static Context mContext;
    private static String url;
    private static Response response;
    private static Request request;
    private static OkHttpClient okHttpClient = new OkHttpClient();
    private static Callback callback;
    private static Map<String, String> map;

    /**
     * 同步get获取数据
     *
     * @return
     */

    private static Response getRequests() {
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 异步get获取数据
     */
    private static void getSyncRequest() {
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    /**
     * post 请求
     */

    private static Response postRequest() {

        FormBody.Builder formBody = new FormBody.Builder();
        for (String key : map.keySet()) {
            formBody.add(key, map.get(key));
        }
        FormBody body = formBody.build();

        request = new Request.Builder().url(url).post(body).build();
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * post 异步请求
     */
    private static void postSyncRequest() {
        FormBody.Builder formBody = new FormBody.Builder();
        for (String key : map.keySet()) {
            formBody.add(key, map.get(key));
        }
        FormBody body = formBody.build();
        request = new Request.Builder().url(url).post(body).build();

        okHttpClient.newCall(request).enqueue(callback);

    }


    @Override
    public Response getRequest(Context context, String url) {

        mContext = context;
        this.url = url;
        if (NetWorkStatus.isNetWorkAvailable(context)) {
            request = new Request.Builder().url(url).build();
            return getRequests();
        } else {
            return response;
        }

    }

    @Override
    public void getSyncRequest(Context context, String url, Callback callback) {
        mContext = context;
        this.url = url;
        this.callback = callback;
        if (NetWorkStatus.isNetWorkAvailable(context)) {
            request = new Request.Builder().url(url).build();
            getSyncRequest();
        }
    }

    @Override
    public Response postReques(Context context, String url, Map<String, String> map) {
        mContext = context;
        this.url = url;
        this.map = map;
        if (NetWorkStatus.isNetWorkAvailable(context)) {
            return postRequest();
        }

        return null;
    }

    @Override
    public void postSyncReques(Context context, String url, Map<String, String> map, Callback callback) {
        mContext = context;
        this.url = url;
        this.map = map;
        this.callback = callback;
        if (NetWorkStatus.isNetWorkAvailable(context)) {
            postSyncRequest();
        }
    }
}
第四步获取数据
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.zzcx.mylibrary.NetOkhttpRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            text.setText(msg.obj.toString());
        }
    };


    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.text);

        /**
         * 同步get
         *
         */
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String url = "http://samples.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric&appid=b1b15e88fa797225412429c1c50c122a1";
//                /**
//                 * dependence netlib
//                 *
//                 */
//                Response response =  new NetOkhttpRequest().getRequest(MainActivity.this,url);
//
//                if(response!=null)
//                if (response.isSuccessful()) {
//                    Gson gson = new Gson();
//                    WeatherBeans weatherBeans = null;
//                    try {
//                        weatherBeans = gson.fromJson(response.body().string(),WeatherBeans.class);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    Log.i( MainActivity.class.getSimpleName(), "onResponse: "+weatherBeans.toString());
//                    Message message = Message.obtain();
//                    message.obj = weatherBeans.toString();
//                    mHandler.sendMessage(message);
//                }
//            }
//        }).start();

        /**
         * 异步get
         */
//      final  String url = "http://samples.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric&appid=b1b15e88fa797225412429c1c50c122a1";
//                    new NetOkhttpRequest().getSyncRequest(MainActivity.this, url,new Callback(){
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//                        }
//                        @Override
//                       public void onResponse(Call call, Response response) throws IOException {
//                           if(response!=null)
//                               if (response.isSuccessful()){
//                                   Message message = Message.obtain();
//                                   message.obj = response.body().string();
//                                   mHandler.sendMessage(message);
//                               }
//                       }
//                   });


//    final  String url = "http://samples.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric&appid=b1b15e88fa797225412429c1c50c122a1";


/**
 * post 请求
 */
        final Map<String, String> map = new HashMap<>();
        map.put("phone", "13429667914");
        map.put("key", "safly");
        String url = "http://apis.juhe.cn/mobile/get?";

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                String url = "http://apis.juhe.cn/mobile/get?";
//                Response response =  new NetOkhttpRequest().postReques(MainActivity.this,url,map);
//                    Message message = Message.obtain();
//                try {
//                    message.obj = response.body().string();
//                    mHandler.sendMessage(message);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();


        /**
         * post 异步
         */

        new NetOkhttpRequest().postSyncReques(this, url, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, @Nullable Response response) throws IOException {
                if (response.isSuccessful()) {
                    Message message = Message.obtain();
                    message.obj = response.body().string();
                    mHandler.sendMessage(message);
                }
            }
        });
    }
}

更早之前

public class Main2Activity extends Activity {

    private OkHttpClient okHttpClient;
    private Request request;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);


       findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {

                  new Thread(new Runnable() {
                      @Override
                      public void run() {

                              getRequest();

                      }
                  }).start();
           }
       });
    }

    public void getRequest()  {
        okHttpClient = new OkHttpClient();
        request = new Request.Builder().url("http://sqw.....om:6661....3800370032003700360038").build();
       //new call
        Call call = okHttpClient.newCall(request);
       call.enqueue(new Callback() {
           @Override
           public void onFailure(Call call, IOException e) {

           }
           @Override
           public void onResponse(Call call, Response response) throws IOException {
           }
       });


        try {

            run();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void run() throws Exception{
        Response response = okHttpClient.newCall(request).execute();
        if(!response.isSuccessful()) throw  new IOException("Unexpected code"+response);
        Headers responseHeaders = response.headers();
        for(int i = 0;i<responseHeaders.size();i++){
          ///  Log.i("responseHeaders",responseHeaders.name(i)+":"+responseHeaders.value(i));
        }

        parseXml(response.body().string());//没明白为什么数据只能用一次~

    }

    private void parseXml(String s) {
        Log.i("response",s);
        StringReader reader = new StringReader(s);
        List<CooperBean> list =null;
        CooperBean cooperBean =null;

        try {
         //   XmlPullParserFactory factory =XmlPullParserFactory.newInstance();
         //   XmlPullParser parser = factory.newPullParser();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(reader);
            int eventType = parser.getEventType();
            Log.i("-go to --","");
            while (eventType != XmlPullParser.END_DOCUMENT){

                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:
                        list = new ArrayList<>();

                        break;
                    case  XmlPullParser.START_TAG:
                        cooperBean = new CooperBean();
                        if("response".equalsIgnoreCase(parser.getName())){
                            Log.i("response",parser.getName());
                            Log.i("description",parser.getAttributeValue("","description"));
                        }
                        if("cooperative".equalsIgnoreCase(parser.getName())){
                            Log.i("cooperative",parser.getName());
                            Log.i("id",parser.getAttributeValue("","id"));
                            Log.i("icon",parser.getAttributeValue("","icon"));
                            Log.i("maintitle",parser.getAttributeValue("","maintitle"));
                          //  Log.i("title",parser.getAttributeValue("","title") == null?null:parser.getAttributeValue("","title"));
                            Log.i("urladdress",parser.getAttributeValue("","urladdress") == null?null:parser.getAttributeValue("","urladdress"));
                            Log.i("version",parser.getAttributeValue("","version"));
                            Log.i("actionid",parser.getAttributeValue("","actionid"));
                            Log.i("inserttime",parser.getAttributeValue("","inserttime"));
                            Log.i("endtime",parser.getAttributeValue("","endtime"));
                            Log.i("status",parser.getAttributeValue("","status"));
                            Log.i("sortnum",parser.getAttributeValue("","sortnum"));
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        list.add(cooperBean);
                        break;
                //    case XmlPullParser.END_DOCUMENT:
               //         break;
                }
                eventType = parser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    class CooperBean{
        String  id;
        String title;
        String icon;
        String maintitle;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public String getMaintitle() {
            return maintitle;
        }

        public void setMaintitle(String maintitle) {
            this.maintitle = maintitle;
        }

        public String getUrladdress() {
            return urladdress;
        }

        public void setUrladdress(String urladdress) {
            this.urladdress = urladdress;
        }

        public String getVerson() {
            return verson;
        }

        public void setVerson(String verson) {
            this.verson = verson;
        }

        public String getActionid() {
            return actionid;
        }

        public void setActionid(String actionid) {
            this.actionid = actionid;
        }

        public String getInserttime() {
            return inserttime;
        }

        public void setInserttime(String inserttime) {
            this.inserttime = inserttime;
        }

        public String getEndtime() {
            return endtime;
        }

        public void setEndtime(String endtime) {
            this.endtime = endtime;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getSortnum() {
            return sortnum;
        }

        public void setSortnum(String sortnum) {
            this.sortnum = sortnum;
        }

        String urladdress;
        String verson;
        String actionid;
        String inserttime;
        String endtime;
        String status;
        String sortnum;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值