okhttp3 的 post 、Get 方式

Post 

OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

String url_base = "http://119.3.56.22/index.php?m=Api&c=Alert&a=postAlert";
String mac = Config.get("mac");
FormBody.Builder builder = new FormBody.Builder();
builder.add("mid",mac);
String s = String.valueOf(code);
builder.add("code",s);
builder.add("description",description);
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
                .url(url_base)
                .post(requestBody)
                .build();
client.newCall(request).enqueue(new Callback() {            
    @Override            
    public void onFailure(Call call, IOException e) {            
    }

           
    @Override            
    public void onResponse(Call call, Response response) throws IOException {                
        String res_str = response.body().string();               
        Log.d("Util", "=postMsg result=>>" + res_str);           
     }        
});

Get:

public static void GetFun(){
        String url = "http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=你申請的key";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默認就是GET請求,可以不寫
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: " + response.body().string());
            }
        });
    }

另一種:

public void GetFun(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                //.url("https://api.weatherbit.io/v2.0/current?city=Raleigh&country=US&key=964a9c0496msh419bdc156c9a765p10d506jsn0a74882bcf8a")
                .url("https://api.weatherbit.io/v2.0/current&city=Raleigh&country=US")
                .get()
                .addHeader("x-rapidapi-host", "weatherbit-v1-mashape.p.rapidapi.com")
                .addHeader("x-rapidapi-key", "964a9c0496msh419bdc156c9a765p10d506jsn0a74882bcf8a")
                .build();

        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            Log.d(TAG, "onResponse: " + response.body().string());
        } else {
            Log.d(TAG, "onFailure: ");
        }
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章