网络请求数据封装

package com.example.monikaoshi.util;

import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by John on 2018/5/2 0002.
 */

public class RequestDataUtil extends AsyncTask<String,Void,String> {

    //2.声明接口对象
    private IcallBack icallBack;
    //3.用构造方法传递一个接口的实现类
    public RequestDataUtil(IcallBack icallBack) {
        this.icallBack = icallBack;
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            if(urlConnection.getResponseCode() == 200){
                InputStream inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                int len;
                byte[] b = new byte[1024];
                while ((len = inputStream.read(b))!=-1){
                    outputStream.write(b,0,len);
                }
                return outputStream.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //4.调用接口中的方法
        icallBack.getJson(s);
    }
    //1.定义接口
    public interface IcallBack{
        //只有申明,没有实现
        void getJson(String jsonData);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_14876513/article/details/80170900