《第一行代码》比较(13)——封装请求网络工具,以及请求回调

package com.zjw.mynetwork8;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

//9.5 p344 网络编程的最佳实践
/*
封装网络请求v1.0
public class HttpUtil {
    public static String sendHttpRequest(String address) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url=new URL(address);
            httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder=new StringBuilder();
            String line;
            while((line=bufferedReader.readLine())!=null){
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }finally {
            if(httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
        }
    }
}
调用:
String address="https://www.baidu.com";
String response=HttpUtil.sendHttpRequest(address);
问题:网络请求为耗时操作要在子线程执行,
如果在sendHttpRequest()方法内部直接开启线程不做其他处理,方法会在服务器还没来得及响应就执行结束了
解决:需要使用Java回调机制
 */
/*
Java回调机制使用流程:
1.定义一个接口:
public interface HttpCallbackListener{
void onFinish(String response);//服务器响应成功时调用
void onError(Exception e);//网络操作出现错误时调用
}
 */
/*
封装网络请求v2.0
public class HttpUtil {
    public static void sendHttpRequest(final String address, final HttpCallbackListener httpCallbackListener) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                try {
                    URL url = new URL(address);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setReadTimeout(5000);
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    if(httpCallbackListener!=null){
                        httpCallbackListener.onFinish(stringBuilder.toString());
                    }
                } catch (Exception e) {
                    if(httpCallbackListener!=null){
                        httpCallbackListener.onError(e);
                    }
                } finally {
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }
}
注意:子线程中是无法通过return语句来返回数据的(run方法没有返回值)
调用:
     String address="https://www.baidu.com";
        HttpUtil.sendHttpRequest(address,new HttpCallbackListener(){

            @Override
            public void onFinish(String response) {

            }

            @Override
            public void onError(Exception e) {

            }
        });
 */
/*
使用OkHttp:
    public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder()
                .url(address)
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }
    OkHttp在enqueue()方法内部以及开了子线程,会在子线程中执行HTTP请求,并将结果回调到okhttp3.Callback中
调用方法:
 HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                String responseData=response.body().toString();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
            }
        });
 */
/*
注意:两者接口回调都是在子线程运行,所以不可以在这里执行UI操作,除非借助runOnUiThread()方法
 */
public class PracticeOfNetwork extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice_of_network);
        String address = "https://www.baidu.com";
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {

            @Override
            public void onFinish(String response) {
                //这里根据返回内容执行具体的逻辑
            }

            @Override
            public void onError(Exception e) {
                //在这里对异常情况进行处理
            }
        });
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                String responseData = response.body().toString();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
            }
        });
    }
}
package com.zjw.mynetwork8;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by hp on 2017/7/26.
 */

public class HttpUtil {
    public static void sendHttpRequest(final String address, final HttpCallbackListener httpCallbackListener) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                try {
                    URL url = new URL(address);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.setReadTimeout(5000);
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    if (httpCallbackListener != null) {
                        httpCallbackListener.onFinish(stringBuilder.toString());
                    }
                } catch (Exception e) {
                    if (httpCallbackListener != null) {
                        httpCallbackListener.onError(e);
                    }
                } finally {
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }

    public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder()
                .url(address)
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }
}

转载于:https://my.oschina.net/u/3620480/blog/1489854

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值