2018年8月13日 星期一

OkHttpClient get 數據

private void getOkhttp(){
runOnUiThread(new Runnable() {
            @Override
            public void run() {

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

  String url="https://www.google.com.tw/";
                Request request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();
           
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("Debug"," get----------onFailure--->");
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       final String string = response.body().string();
                    //    byte[] b = response.body().bytes(); //获取数据的bytes
                   //  String info = new String(b, "gb2312"); //然后将其转为gb2312
                   
                    }
                });

            }
        });
}


    public void get2(){

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


        //post
        String a="050";
        String b="050"; 

        RequestBody requestBodyPost = new FormBody.Builder()
                .add("a", a)
                .add("b", b)
                .build();
         Request requestPost = new Request.Builder()
                .url("https://www.google.com.tw/"+a+b)
                .post(requestBodyPost)
                .build();
        client.newCall(requestPost).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("Debug"," post----------onFailure--->");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
             //   final String string = response.body().string();
             //okhttp的锅…response.body().string()中的string()方法只能调用一次……….坑死
                String html = new String(response.body().bytes(), "big5");
               

            }
        });

    }

沒有留言:

張貼留言