浅析okhttp开源框架

首先看下官方介绍和github源码

官方介绍
Github源码

自己写的简单的使用例子

这里写图片描述

因为服务器出了点问题 所以提交表单中的三个功能没有展示出来,但是我会把代码贴出来的

再看下官方给的简单例子

/*GET*/
OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}
/*POST*/
public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

下面是我自己写的代码

package com.example.hfs.android_30_01_okhttp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

/** * MainActivity */
public class MainActivity extends AppCompatActivity {

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

    public void btnClick(View view){
        Intent intent=null;
        if(R.id.btn_down_img==view.getId()){
             intent=new Intent(this,ImageDownActivity.class);
        }else{
            intent=new Intent(this,FormActivity.class);
        }
        startActivity(intent);
    }
}
package com.example.hfs.android_30_01_okhttp;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;

/** * loadImage */
public class ImageDownActivity extends AppCompatActivity {
    private ImageView img;
    private static final String IMAGE_PATH_ONE = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png";
    private static final String IMAGE_PATH_TWO = "http://a.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c29870b98d52a6059252da62e.jpg";
    private OkHttpUtils okHttpUtils;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==0x200){
                img.setImageBitmap((Bitmap) msg.obj);
            }
        }
    };

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

        img= (ImageView) findViewById(R.id.img);
        okHttpUtils=new OkHttpUtils();
    }

    public void downImg(View view){
        if(R.id.btn_down_one==view.getId()){
            //(IMAGE_PATH_ONE);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap= null;
                    try {
                        bitmap = okHttpUtils.getBitmap(IMAGE_PATH_ONE);
                        Message msg=handler.obtainMessage();
                        msg.what=0x200;
                        msg.obj=bitmap;
                        handler.sendMessage(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }).start();

        }else{
            okHttpUtils.setBitmapAsync(IMAGE_PATH_TWO, this, img);
        }
    }
}
package com.example.hfs.android_30_01_okhttp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

/** * Form */
public class FormActivity extends AppCompatActivity {
    private EditText et_name, et_age, et_tel, post_et_image;
    private TextView tv;
    private  OkHttpUtils okHttpUtils;


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

        et_name = (EditText) findViewById(R.id.et_name);
        et_age = (EditText) findViewById(R.id.et_age);
        et_tel = (EditText) findViewById(R.id.et_tel);
        post_et_image = (EditText) findViewById(R.id.post_et_image);

        tv = (TextView) findViewById(R.id.tv);

        okHttpUtils=new OkHttpUtils();
    }

    public void btnClick(View v) {

        Person person = new Person();

        // 设置姓名
        person.setName(et_name.getText().toString());
        person.setAge(Integer.parseInt(et_age.getText().toString()));
        person.setTel(et_tel.getText().toString());
        person.setImgname(post_et_image.getText().toString());

        switch (v.getId()) {
            case R.id.get_btn:

                okHttpUtils.SubmitDataByGet(person,this,tv);

                break;
            case R.id.post_btn:
                okHttpUtils.SubmitDataByPostKeyValue(person,this,tv);
                break;
            case R.id.post_img_btn:
                okHttpUtils.SubmitDataByPostFile(person,this,tv);
                break;
        }

    }
}
package com.example.hfs.android_30_01_okhttp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/** * Utils */
public class OkHttpUtils {
    private OkHttpClient okHttpClient;

    public OkHttpUtils() {
        this.okHttpClient = new OkHttpClient();
    }

    /** * 同步方式 */
    public Bitmap getBitmap(String imagePathOne) throws IOException {
        // 1 创建一个Request对象
        Request request = new Request.Builder().url(imagePathOne).build();
        // 2 创建一个Call对象,用于调用request
        Call call = okHttpClient.newCall(request);

        // 3 得到返回对象
        Response response = call.execute();// 这个方法为同步方法

        if (response.isSuccessful()) {
            // 这是获取到的结果输入流
            InputStream inStream = response.body().byteStream();
            return BitmapFactory.decodeStream(inStream);
        }
        return null;

    }

    /** * 异步方式 */
    public void setBitmapAsync(String imagePathTwo, final ImageDownActivity imageDownActivity, final ImageView img) {

        // 1 创建一个Request对象
        Request request = new Request.Builder().url(imagePathTwo).build();

        // 2 创建一个Call对象,用于调用request
        Call call = okHttpClient.newCall(request);

        // 3 执行异步请求,Callback中的所有方法,都是在子线程中完成
        call.enqueue(new Callback() {
            // 请求失败时调用
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                Toast.makeText(imageDownActivity, "加载失败!", Toast.LENGTH_SHORT).show();
            }

            //正常请求结束时调用
            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 显示
                    final Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                    imageDownActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            img.setImageBitmap(bitmap);
                        }
                    });
                }
            }
        });


    }

    /** * get方式提交 */
    public void SubmitDataByGet(Person person, final FormActivity formActivity, final TextView tv) {
        //http://10.30.153.147:8080/AndroidProjectServer/GetPostServlet?name=zh&age=12&tel=111
        String Base_Url = "http://10.30.153.176:8080/MyServer/GetPostServlet";
        String param_Url = "?name=" + person.getName() + "&age=" + person.getAge() + "&tel=" + person.getTel();

        Request request = new Request.Builder().url(Base_Url + param_Url).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                formActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("连接失败,请重试!");
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String result = "提交失败!";
                if (response.isSuccessful() && "Success".equals(response.body().string())) {
                    result = "提交成功!";
                }

                final String finalResult = result;
                formActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(finalResult);
                    }
                });

            }
        });
    }

    /** * 以post方式,采取键值对的形式进行提交 */
    public void SubmitDataByPostKeyValue(Person person, final FormActivity formActivity, final TextView tv) {
        String Base_Url = "http://10.30.153.176:8080/MyServer/GetPostServlet";

        //name=zh&age=12&tel=111
        RequestBody requestBody = new FormEncodingBuilder()
                .add("name", person.getName())
                .add("age", person.getAge() + "")
                .add("tel", person.getTel())
                .build();


        Request request = new Request.Builder().url(Base_Url).post(requestBody).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                formActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("连接失败,请重试!");
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String result = "提交失败!";
                if (response.isSuccessful() && "Success".equals(response.body().string())) {
                    result = "提交成功!";
                }

                final String finalResult = result;
                formActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(finalResult);
                    }
                });

            }
        });
    }


    /** * 上传文件和文本 */
    public void SubmitDataByPostFile(Person person, final FormActivity formActivity, final TextView tv) {
        String Base_Url = "http://10.30.153.176:8080/MyServer/UpdateServlet";
        File file = new File(Environment.getExternalStorageDirectory(), person.getImgname());

        if (file.exists()) {
            Log.i("TAG","true");
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);

            RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addPart(Headers.of("Content-Disposition", "form-data; name="name""), RequestBody.create(null, person.getName()))
                    .addPart(Headers.of("Content-Disposition", "form-data; name="age""), RequestBody.create(null, person.getAge() + ""))
                    .addPart(Headers.of("Content-Disposition", "form-data; name="tel""), RequestBody.create(null, person.getTel()))
                    .addPart(Headers.of("Content-Disposition", "form-data; name="image"; filename="" + person.getImgname() + """), fileBody)
                    .build();

            final Request request=new Request.Builder().url(Base_Url).post(requestBody).build();
            Call call=okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    e.printStackTrace();
                    formActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText("连接服务端失败!");
                        }
                    });
                }
                @Override
                public void onResponse(Response response) throws IOException {
                    String result = "POST提交普通数据与文件失败!";
                    if (response.isSuccessful() && "Success".equals(response.body().string())) {
                        result = "POST提交普通数据与文件成功!";
                    }
                    final String finalResult = result;
                    formActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText(finalResult);
                        }
                    });
                }
            });
        }

    }
}

推荐文章

Android java支持绑定服务和活动之间的FIFO数据传输?

Android java支持绑定服务和活动之间的FIFO数据传输?

推荐文章

2008年SSRS报表查看器版本

2008年SSRS报表查看器版本

推荐文章

用java中的socket连接测量网络使用

用java中的socket连接测量网络使用

推荐文章

如何在mvc2中使用jQuery在提交表单之前手动调用表单验证

如何在mvc2中使用jQuery在提交表单之前手动调用表单验证

推荐文章

在JavaScript中使用常量有什么意义?

在JavaScript中使用常量有什么意义?

推荐文章

jsp可靠热部署

jsp可靠热部署

推荐文章

我能在我的网站上用python编写浏览器游戏吗

我能在我的网站上用python编写浏览器游戏吗

推荐文章

如何在android中同时使用BallonItemizedOverlay和双击并长时间点击地图?

如何在android中同时使用BallonItemizedOverlay和双击并长时间点击地图?

推荐文章

如何查看android中的电池使用设置?

如何查看android中的电池使用设置?

推荐文章

如何在移动样板中添加对话框?

如何在移动样板中添加对话框?

推荐文章

Outlook加载项事件C#

Outlook加载项事件C#

推荐文章

HTML中带有xml输入的主细节jqGrid

HTML中带有xml输入的主细节jqGrid

推荐文章

Chrome中的动画跳跃

Chrome中的动画跳跃

推荐文章

编写jquery选择器以选择具有特定模式的类

编写jquery选择器以选择具有特定模式的类

推荐文章

界面生成器-使用布局视图框

界面生成器-使用布局视图框

推荐文章

模式表单中的Autoscroll UITableView

模式表单中的Autoscroll UITableView