博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
okhttp 示例_OkHttp Android示例教程
阅读量:2543 次
发布时间:2019-05-11

本文共 10801 字,大约阅读时间需要 36 分钟。

okhttp 示例

OkHttp is a third party library that was introduced by Square in 2013 for sending and receive HTTP-based network requests.

OkHttp是Square在2013年引入的第三方库,用于发送和接收基于HTTP的网络请求。

OkHttp Android (OkHttp Android)

Initially Android had only two HTTP clients: HttpURLConnection and Apache HTTP Client; for sending and receiving data from the web. Each of these clients required a lot of boilerplate code to be written inside the AsyncTask or the background thread methods. Moreover, these clients have their own sets of limitations when it came to cancelling an HTTP request or connection-pooling.

最初,Android只有两个HTTP客户端: HttpURLConnectionApache HTTP Client ; 用于从网络发送和接收数据。 这些客户端中的每个客户端都需要在AsyncTask或后台线程方法中编写大量样板代码。 此外,这些客户端在取消HTTP请求或连接池方面有其自身的限制。

OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.

OkHttp android通过直接在Java Socket的顶部工作而无需使用任何其他依赖项,从而提供HttpURLConnectionApache Client接口的实现。

OkHttp Android的优势 (OkHttp Android Advantages)

Some advantages that OkHttp brings to us are:

OkHttp给我们带来的一些好处是:

  1. Connection pooling

    连接池
  2. Gziping

    压缩
  3. Caching

    快取
  4. Recovering from network problems

    从网络问题中恢复
  5. Redirects

    重新导向
  6. Retries

    重试
  7. Support for synchronous and asynchronous calls

    支持同步和异步调用

同步与异步调用 (Synchronous vs Asynchronous calls)

  • Synchronous calls require an AsyncTask wrapper around it. That means it doesn’t support cancelling a request. Also, AsyncTasks generally leak the Activity’s context, which is not preferred.

    同步调用需要围绕它的AsyncTask包装器。 这意味着它不支持取消请求。 另外,AsyncTasks通常会泄漏Activity的上下文,这不是首选。
  • Asynchronous Calling is the recommneded way since it supports native cancelling, tagging multiple requests and canceling them all with a single method call (by invoking the cancel on the Acitivty instance inside the onPause or onDestroy method).

    推荐使用异步调用,因为它支持本机取消,标记多个请求并通过单个方法调用将它们全部取消(通过在onPauseonDestroy方法内在Acitivty实例上调用cancel)。

Before we look into the implementation of OkHttp android, add the following dependency

在我们研究OkHttp android的实现之前,请添加以下依赖项

compile 'com.squareup.okhttp3:okhttps:3.4.1'

Add the permission for internet inside the AndroidManifest.xml file.

AndroidManifest.xml文件中添加Internet权限。

OkHttp Android示例代码 (OkHttp Android Example Code)

The MainActivity.java for Synchronous Calls is given below.

下面给出了用于同步调用的MainActivity.java。

package com.journaldev.okhttp;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.json.JSONException;import org.json.JSONObject;import java.io.IOException;import okhttp3.Call;import okhttp3.Callback;import okhttp3.MediaType;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;public class MainActivity extends AppCompatActivity {    OkHttpClient client = new OkHttpClient();    TextView txtString;    public String url= "https://reqres.in/api/users/2";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        txtString= (TextView)findViewById(R.id.txtString);        OkHttpHandler okHttpHandler= new OkHttpHandler();        okHttpHandler.execute(url);    }    public class OkHttpHandler extends AsyncTask {        OkHttpClient client = new OkHttpClient();        @Override        protected String doInBackground(String...params) {            Request.Builder builder = new Request.Builder();            builder.url(params[0]);            Request request = builder.build();            try {                Response response = client.newCall(request).execute();                return response.body().string();            }catch (Exception e){                e.printStackTrace();            }            return null;        }        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            txtString.setText(s);        }    }}

For Asynchronous Calls the MainActivity.java should be defined as:

对于异步调用,MainActivity.java应该定义为:

package com.journaldev.okhttp;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.json.JSONException;import org.json.JSONObject;import java.io.IOException;import okhttp3.Call;import okhttp3.Callback;import okhttp3.MediaType;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;public class MainActivity extends AppCompatActivity {        TextView txtString;    public String url= "https://reqres.in/api/users/2";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        txtString= (TextView)findViewById(R.id.txtString);        try {            run();        } catch (IOException e) {            e.printStackTrace();        }    }    void run() throws IOException {        OkHttpClient client = new OkHttpClient();        Request request = new Request.Builder()                .url(url)                .build();        client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                call.cancel();            }            @Override            public void onResponse(Call call, Response response) throws IOException {                final String myResponse = response.body().string();                MainActivity.this.runOnUiThread(new Runnable() {                    @Override                    public void run() {                        txtString.setText(myResponse);                    }                });            }        });    }}

We’ve used a test API from .

我们从使用了测试API。

The response string returned is of the JSON format that gets printed on the screen.

返回的响应字符串为JSON格式,并在屏幕上打印出来。

You can try out other open source API’s like Github API, Stackoverflow etc.

您可以尝试其他开源API,例如Github API,Stackoverflow等。

OkHttp查询参数示例 (OkHttp Query Parameters Example)

If there are any query parameters we can easily pass them using an HttpUrl.Builder class.

如果有任何查询参数,我们可以使用HttpUrl.Builder类轻松地传递它们。

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://httpbin.org/get).newBuilder();urlBuilder.addQueryParameter("website", "www.journaldev.com");urlBuilder.addQueryParameter("tutorials", "android");String url = urlBuilder.build().toString();Request request = new Request.Builder()                     .url(url)                     .build();

The above url was obtained from .

以上网址是从获得的。

OkHttp Android标头示例 (OkHttp Android Headers Example)

If there are any authenticated query parameters, they can be added in the form of headers as shown below:

如果有任何经过身份验证的查询参数,则可以以标头的形式添加它们,如下所示:

Request request = new Request.Builder()    .header("Authorization", "replace this text with your token")    .url("your api url")    .build();

处理JSON响应 (Processing the JSON Response)

We can parse the JSON data to get the relevant params and display them in a TextView as below code.

我们可以解析JSON数据以获取相关的参数,并将其显示在TextView中,如下代码所示。

client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                call.cancel();            }            @Override            public void onResponse(Call call, Response response) throws IOException {                final String myResponse = response.body().string();                MainActivity.this.runOnUiThread(new Runnable() {                    @Override                    public void run() {                        try {                            JSONObject json = new JSONObject(myResponse);                            txtString.setText(json.getJSONObject("data").getString("first_name")+ " "+json.getJSONObject("data").getString("last_name"));                        } catch (JSONException e) {                            e.printStackTrace();                        }                    }                });            }        });

OkHttp Android POST示例 (OkHttp Android POST Example)

Up until now, we’ve looked at getting a response by calling a few API’s. To post a data to the server we need to build our request in the following way.

到目前为止,我们一直在通过调用一些API来获得响应。 要将数据发布到服务器,我们需要通过以下方式构建请求。

public class MainActivity extends AppCompatActivity {    public String postUrl= "https://reqres.in/api/users/";    public String postBody="{\n" +            "    \"name\": \"morpheus\",\n" +            "    \"job\": \"leader\"\n" +            "}";    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        try {            postRequest(postUrl,postBody);        } catch (IOException e) {            e.printStackTrace();        }    }    void postRequest(String postUrl,String postBody) throws IOException {        OkHttpClient client = new OkHttpClient();        RequestBody body = RequestBody.create(JSON, postBody);        Request request = new Request.Builder()                .url(postUrl)                .post(body)                .build();        client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                call.cancel();            }            @Override            public void onResponse(Call call, Response response) throws IOException {                Log.d("TAG",response.body().string());            }        });    }}

In the above code, we’ve used the MediaType class that’s a part of OkHttp to define the type of data being passed. We’ve used the test API URL from .

在上面的代码中,我们使用了OkHttp一部分的MediaType类来定义要传递的数据类型。 我们使用了的测试API URL。

The post(RequestBody body) method is called on the RequestBuilder with the relevant value.

将在PostBuilder上使用相关值调用post(RequestBody body)方法。

The Log displays the following response.

日志显示以下响应。

{"name":"morpheus","job":"leader","id":"731","createdAt":"2017-01-03T17:26:05.158Z"}.

{"name":"morpheus","job":"leader","id":"731","createdAt":"2017-01-03T17:26:05.158Z"}

OkHttp is the recommend HttpClient that’s used inside the Retrofit Networking Library. We’ll look into this in the next tutorial.

OkHttp是在改造网络库中使用的推荐HttpClient。 我们将在下一个教程中对此进行研究。

We’ve added three buttons in the layout to invoke each of the methods, postRequest(), run() and the AsyncTask wrapper class.

我们在布局中添加了三个按钮来调用每个方法postRequest(),run()和AsyncTask包装器类。

You can download the final Android OkHttp Project from the link below.

您可以从下面的链接下载最终的Android OkHttp项目。

翻译自:

okhttp 示例

转载地址:http://aqlzd.baihongyu.com/

你可能感兴趣的文章
一般处理程序在VS2012中打开问题
查看>>
C语言中的++和--
查看>>
thinkphp3.2.3入口文件详解
查看>>
POJ 1141 Brackets Sequence
查看>>
Ubuntu 18.04 root 使用ssh密钥远程登陆
查看>>
Servlet和JSP的异同。
查看>>
虚拟机centOs Linux与Windows之间的文件传输
查看>>
ethereum(以太坊)(二)--合约中属性和行为的访问权限
查看>>
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>
vs无法加载项目
查看>>
Beanutils基本用法
查看>>
玉伯的一道课后题题解(关于 IEEE 754 双精度浮点型精度损失)
查看>>
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>