Android OkHttp基本用法

okhttp引用设置

    Android studio添加引用okhttp.jar包

    注意:build.gradle中总共2个添加
    compile 'com.squareup.okio:okio:1.5.0'
    compile 'com.squareup.okhttp:okhttp:2.4.0'

    描述:
    关键1:使用前,对于Android Studio的用户,可以选择添加:
    compile 'com.squareup.okhttp:okhttp:2.4.0'

    关键2:okhttp内部依赖okio,所以,别忘了同时导入okio:
    compile 'com.squareup.okio:okio:1.5.0'

    具体操作如下:
    在app文件夹 ->

    build.gradle文件添加相应代码 ->
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.1.1'

        compile 'com.squareup.okio:okio:1.5.0'
        compile 'com.squareup.okhttp:okhttp:2.5.0'

        compile files('libs/gson-2.2.1.jar')
        compile files('libs/okhttp-2.3.0.jar')
        
        注意:compile files('libs/okhttp-2.3.0.jar')是手动添加jar文件生成的代码,
              compile 'com.squareup.okhttp:okhttp:2.5.0'是用系统搜寻出来的格式
              2者之中保留一个即可。
    }

    修改完毕点击右上角"Sync Now" ->

    注意:配置Android权限,设置允许网络请求
    在AndroidManifest.xml文件中

===============================================
关键类:RequestBody添加参数
        RequestBody formBody = new FormEncodingBuilder()
        .add("platform", "android")
        .add("name", "bug")
        .add("subject", "XXXXXXXXXXXXXXX")
        .build();

关键类:Request
        Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();

关键类:Response
        Response response = client.newCall(request).execute();

关键类:call.enqueue:以异步的方式去执行请求,所以调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,在Callback中即可得到结果。
        Call call = mOkHttpClient.newCall(request); 
        //请求加入调度
        call.enqueue(new Callback()
                {
                    @Override
                    public void onFailure(Request request, IOException e)
                    {
                    }


                    @Override
                    public void onResponse(final Response response) throws IOException
                    {
                            //String htmlStr =  response.body().string();
                    }
        }); 

网络请求权限设置

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.info.activity">
        <uses-permission android:name="android.permission.INTERNET"/>(设置允许网络请求)
    </manifest>


=========================================================HTTP请求之 同步 GET请求=========================================================
private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    Request request = new Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response);
    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }
    System.out.println(response.body().string());
}

Response类的string()方法会把文档的所有内容加载到内存,适用于小文档,对应大于1M的文档,应   使用流()的方式获取。
response.body().byteStream()

=========================================================HTTP请求之 异步 GET请求=========================================================
private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    Request request = new Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }

            System.out.println(response.body().string());
        }
    });
}

读取响应会阻塞当前线程,所以发起请求是在主线程,回调的内容在非主线程中。
=========================================================HTTP请求之POST方式提交字符串=========================================================
private static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    String postBody = ""
            + "Releases\n"
            + "--------\n"
            + "\n"
            + " * _1.0_ May 6, 2013\n"
            + " * _1.1_ June 15, 2013\n"
            + " * _1.2_ August 11, 2013\n";

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}
因为整个请求体都在内存中,应避免提交1M以上的文件
=========================================================HTTP请求之POST方式提交流=========================================================
private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
        @Override
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n) return factor(x) + " × " + i;
            }
            return Integer.toString(n);
        }
    };

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}
使用Okio框架以流的形式将内容写入,这种方式不会出现内存溢出问题。
=========================================================HTTP请求之POST方式提交文件=========================================================
public static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    File file = new File("README.md");

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}
=========================================================HTTP请求之POST方式提交表单=========================================================
private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
            .add("search", "Jurassic Park")
            .build();
    Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(formBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

表单的每个Names-Values都进行了URL编码。如果服务器端接口未进行URL编码,可定制个  FormBuilder。
=========================================================HTTP请求之文件上传(兼容html文件上传)=========================================================
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
                    RequestBody.create(null, "Square Logo"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"image\""),
                    RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url("https://api.imgur.com/3/image")
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) 
        throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}



代码实例


XML文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.info.activity.Main2Activity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button666"
        android:id="@+id/button4"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>


Activity文件


package com.info.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.info.config.ConstantInfo;
import com.info.model.UserView;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Main2Activity extends AppCompatActivity {

    private Button btnLogin;

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

        btnLogin = (Button) findViewById(R.id.button4);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String result = run();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public String run() throws IOException {
        String loginUrl = "http://192.168.1.41:8023/api/user/login";
        RequestBody formBody = new FormEncodingBuilder()
                .add("UserName", "admin")
                .add("Password", "000000")
                .build();
        OkHttpClient mOkHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(loginUrl)
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String jsonResult =  response.body().string();
                Gson gson=new Gson();
                UserView model = gson.fromJson(jsonResult,UserView.class);
                Log.e("T", jsonResult);
                Log.e("r", model.getData().getUserName());
            }
        });

        return "";
    }
}


升级版,封装Okhttp工具类,待续...


你可能感兴趣的:(call,callback,okhttp,ENQUEUE)