okhttp3的使用

例一:execute的用法,代碼如下所示:

public class MainActivity extends AppCompatActivity {
    private Button button;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient okHttpClient = new OkHttpClient();
                       /* 如果發(fā)起一條POST請求要比GET請求復(fù)雜一點,代碼如下:
                        RequestBody requestBody=new FormBody.Builder()
                                .add("username","admin")
                                .add("password","12345")
                                .build();
                        Request request = new Request.Builder()
                                .url("http://www.baidu.com")
                                .post(requestBody)//在這里調(diào)用post
                                .build();*/
                        Request request = new Request.Builder()
                                .url("http://www.baidu.com")
                                .build();
                        try {
                            Response response = okHttpClient.newCall(request).execute();
                            final String responsedata = response.body().string();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textView.setText(responsedata);
                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                ).start();
            }
        });
    }
}

例二:enqueue的用法,代碼如下所示:

public class MainActivity extends AppCompatActivity {
    private Button button;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://www.baidu.com")
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {//enqueue與execute不同之處就在于,enqueue內(nèi)部已經(jīng)創(chuàng)建好了子線程,就不需要自己再創(chuàng)建了
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {//被外部類調(diào)用的變量就需要加上final,并且加上final之后,這個變量將不能再給其指定新的堆地址或者是值
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    textView.setText(response.body().string());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
            }
        });
    }
}

例三:post請求,以字符串的形式寫入數(shù)據(jù),代碼如下所示:

OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType=MediaType.parse("text/x-markdown; charset=utf-8");
        Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(RequestBody.create(mediaType,"我是付晶晶")).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("MainActivity", "response.body():" + response.body().string());
                //輸出結(jié)果為:06-29 17:28:26.210 27763-27791/jiankang.liang.com.ceshi D/MainActivity: response.body():<p>我是付晶晶</p>
            }
        });

例四:post請求,以流的形式寫入數(shù)據(jù),代碼如下所示:

OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody=new RequestBody() {
            @Nullable
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.write("提交流".getBytes());
            }
        };
        Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(requestBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("MainActivity", "response.body():" + response.body().string());
                //輸出結(jié)果為:06-29 17:48:48.620 32505-32539/jiankang.liang.com.ceshi D/MainActivity: response.body():<p>提交流</p>
            }
        });

例五:post請求,上傳文件到服務(wù)器,代碼如下所示:

 OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType=MediaType.parse("text/x-markdown; charset=utf-8");
        File file=new File("/storage/emulated/0/ceshi.txt");
        RequestBody requestBody=RequestBody.create(mediaType,file);
        Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(requestBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("MainActivity", "response.body():" + response.body().string());
                //輸出結(jié)果為:06-29 22:54:48.735 27302-27336/jiankang.liang.com.ceshi D/MainActivity: response.body():<p>woshiceshiwenjian</p>
            }
        });

例六:post請求,提交表單數(shù)據(jù)到服務(wù)器,代碼如下所示:

  OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder().add("search", "Jurassic Park").build();
        Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(requestBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("MainActivity", "response.body():" + response.body().string());
                /*輸出結(jié)果為:response.body():<!DOCTYPE html>
                <html class="client-nojs" lang="en" dir="ltr">
                <head>
                <meta charset="UTF-8"/>
                <title>Jurassic Park - Wikipedia</title>
                <script>document.documentElement.className = document.documentElement.className.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );</script>
                <script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNames" +
                        "paceNumber":0,"wgPageName":"Jurassic_Park","wgTitle":"Jurassic Park","wgCurRevisionId":847989431,"wgRevisionId":847989431,
                        "wgArticleId":11056991,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCat" +
                        "egories":["Pages using citations with format and no URL","All articles with dead external links","Articles with dead external" +
                        " links from December 2017","Articles with permanently dead external links","Wikipedia indefinitely move-protected pages","Use md" +
                        "y dates from June 2011","Wikipedia articles needing clarification from May 2016","Jurassic Park","Dinosaurs in fiction","Film serie" +
                        "s introduced in 1993","Films set in amusement parks","Universal Studios franchises","Cloning in fiction","Genetic engineering in ficti" +
                        "on","Science fiction films by series","Techno-thriller films","Amusement parks in fiction","Films adapted into video games","Films adapted...*/
                    }
        });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容