封装的Http网络连接请求工具类

package example.com.networktest.utility;

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

import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Http网络连接请求工具类
 * @author zpf
 */
public class HttpUtil {

    /**
     * 使用HttpURLConnection类实现Http连接通讯
     * @param address   网址
     * @param listener  网络请求结果的通知接口
     */
    public static void sendRequestWithHttpURLConnection(final String address , final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream is = connection.getInputStream();
                    //下面对获取的输入流进行读取操作
                    reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        //readLine()方法读取每一行数据,但不包括行尾截止符,如换行符/回车符
                        response.append(line+"\n");
                    }
                    if (listener != null) {
                        //服务器成功响应,回调onFinish()方法
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    //回调onError()方法通知出现网络操作异常
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 使用OkHttp类实现Http连接通讯
     * @param address   请求网址
     * @param responseCallback  响应结果通知接口
     */
    public static void sendRequestWithOkHttp(String address, okhttp3.Callback responseCallback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(responseCallback);
    }

}

你可能感兴趣的:(封装的Http网络连接请求工具类)