美文网首页
HttpUrlConnection

HttpUrlConnection

作者: dev晴天 | 来源:发表于2018-08-11 18:51 被阅读0次
    package com.example.administrator.day4httpurlconnectiondemo.utils;
    
    import android.support.annotation.NonNull;
    import android.util.Log;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    /**
     * Created by Administrator on 2017/11/30.
     * 网络请求类的封装 使用:类直接调用静态方法
     */
    
    public class HttpUtils {
    
        public static void SendHttpRequest(final String urlAddress, final CallBackListener listener){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringBuilder sb=null;
                    HttpURLConnection connection = null;
                    try {
                        URL url = new URL(urlAddress);//获得一个url对象
                        connection = (HttpURLConnection) url.openConnection();//获得HttpURLConnection对象
               /* 请求的一些设置*/
                        connection.setRequestMethod("GET");//get 必须大写
                        connection.setConnectTimeout(5000);
                        connection.setReadTimeout(5000);
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        //在网上请求数据 得到返回数据都是以流的形式返回
                        InputStream in= connection.getInputStream();
                        BufferedReader buff= new BufferedReader(new InputStreamReader(in));
                        sb =  new StringBuilder();
                        String line = null;
    
                        while((line=buff.readLine())!=null){
                            sb.append(line);
                        }
                        if (listener!=null){
                            //请求成功
                            listener.onfinish(sb.toString());
                        }
    
                    } catch (Exception e) {
                        if (listener!=null){
                            // 请求失败
                            Log.i("网址有误!!!", "run: ");
                            listener.onError(e);
    
                        }
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        public interface CallBackListener{
            void onfinish(String s);
            void onError(Exception e);
        }
    }
    

    相关文章

      网友评论

          本文标题:HttpUrlConnection

          本文链接:https://www.haomeiwen.com/subject/nxodbftx.html