OkHttp的使用

效果图:


image.png

一 ,添加联网 权限
二, 添加 butterknife 快速点击事件
MainActivity中的代码


···
package com.example.wangye.androidxmlc_class12;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

@InjectView(R.id.button)
Button btGet;
@InjectView(R.id.button2)
Button btPost;
@InjectView(R.id.button3)
Button btDown;
@InjectView(R.id.textView)
TextView textView;
@InjectView(R.id.imageView)
ImageView imageView;

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

@OnClick({R.id.button, R.id.button2, R.id.button3})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.button:
            getDataByOKGet();
            break;
        case R.id.button2:
            getDataByOKPost();
            break;
        case R.id.button3:
            getDataByOKDown();
            break;
    }
}


public void getDataByOKGet(){
    OkHttpClient okHttpClient = new OkHttpClient();
    Request.Builder builder = new Request.Builder();
    try {
        Request request = builder
                .get()
                .url("http://apicloud.mob.com/environment/query?key=26b2b13b4b440&city="
                        + URLEncoder.encode("哈尔滨","UTF-8")
                        +"&province="
                        +URLEncoder.encode("黑龙江","UTF-8"))
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Thread(){
                    @Override
                    public void run() {
                        try {
                            textView.setText(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }


}


public void getDataByOKPost(){
    try {
    OkHttpClient okHttpClient = new OkHttpClient();

    FormBody.Builder build = new FormBody.Builder();
    RequestBody requestBody = build

// .add("city",URLEncoder.encode("哈尔滨","UTF-8"))
// .add("province",URLEncoder.encode("黑龙江","UTF-8"))
.add("key",URLEncoder.encode("26b2b13b4b440","UTF-8")).build();

    Request.Builder builder = new Request.Builder();

        Request request = builder
                .post(requestBody)
                .url("http://apicloud.mob.com/v1/postcode/pcd")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
               final String s = response.body().string();
                runOnUiThread(new Thread(){
                    @Override
                    public void run() {
                        try {
                            textView.setText(s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }


}


public void getDataByOKDown(){
    try {
        OkHttpClient okHttpClient = new OkHttpClient();

        FormBody.Builder build = new FormBody.Builder();
        RequestBody requestBody = build.build();
        Request.Builder builder = new Request.Builder();
        Request request = builder
                .post(requestBody)
                .url("http://pic2.sc.chinaz.com/files/pic/pic9/201808/zzpic13391.jpg")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                InputStream is = response.body().byteStream();
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                byte buffer[] = new byte[512];
                int length = -1;
                while(  (length = is.read(buffer)) != -1  ){
                    bs.write(buffer,0,length);
                    bs.flush();
                }

                final File file = new File(
                        Environment.getExternalStorageDirectory()+"/1233.jpg");
                FileOutputStream fs = new FileOutputStream(file);

                byte data[] = bs.toByteArray();
                fs.write(data,0,data.length);
                fs.flush();
                is.close();
                bs.close();
                fs.close();
                runOnUiThread(new Thread(){
                    @Override
                    public void run() {
                        imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                    }
                });
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }


}

}

···

你可能感兴趣的:(OkHttp的使用)