HttpURLConnection 请求网络数据 简单使用(成功方法)

import android.os.Handler;
import android.os.Message;
import com.google.common.io.CharStreams;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpHelper {
private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //用传进来的msg 返回字符串
        String s1 = (String) msg.obj;
        //去下面定义接口
        //调用接口的方法
        httpListener.success(s1);

    }
};
private HttpListener httpListener;

//公共的类名
public HttpHelper(){}

//doget  方法
public HttpHelper doget(String s){
    //获取网络数据的方法
    dohttp(s);
    //记得返回this  强转
    return this;
}

//请求网络数据的方法 传字符串
public void dohttp(final String s){
    //new 线程 点开始 run 方法
    new Thread(){
        @Override
        public void run() {
            super.run();
            //new url  传字符串 返回值
            try {
                URL url = new URL(s);
                //用url 开启con  返回http
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //设置请求方式
                connection.setRequestMethod("GET");
                //设置连接超时
                connection.setConnectTimeout(5000);
                //设置读取数据超时
                connection.setReadTimeout(5000);
                //判断成功
                if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                    //引入依赖 gson guava
                    //调用方法
                    String s1 = CharStreams.toString(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                    //信息点ob
                    Message message = Message.obtain();
                    //信息点obj
                    message.obj=s1;
                    //handler 发送消息
                    handler.sendMessage(message);

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

//接口回调
public void result(HttpListener httpListener){
    //接口返回值 this. 提上去
    this.httpListener = httpListener;
}

//定义接口
public interface HttpListener{
    //成功方法传字符串
    void success(String s1);
}
}

你可能感兴趣的:(HttpURLConnection 请求网络数据 简单使用(成功方法))