工具类

//

MyTask   查询网络数据

package animtest.com.example.e531.listview_requestdata.Utils;

import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 使用AsyncTask+HttpURLConnection请求数据
 * Created by e531 on 2017/10/12.
 */
public class MyTask extends AsyncTask<String,Void,String> {

    //申请一个接口类对象
    private  Icallbacks icallbacks;

    //将无参构造设置成私有的,使之在外部不能够调用
    private MyTask(){}
    
    //定义有参构造方法
    public MyTask(Icallbacks icallbacks) {
        this.icallbacks = icallbacks;
    }

    
    protected String doInBackground(String... params) {
        String str="";

        try {
             //使用HttpUrlConnection
            URL url=new URL(params[0]);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            if(connection.getResponseCode()==200){
                InputStream inputStream=connection.getInputStream();
                //调用工具类中的静态方法
                str=ToString.gai(inputStream,"utf-8");
            }

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

        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //解析,封装到bean,更新ui组件
        icallbacks.updateUiByjson(s);



    }
    //定义一个接口
    public interface Icallbacks{
        /**
         * 根据回传的json字符串,解析并更新页面组件
         * @param jsonstr
         */
        void updateUiByjson(String jsonstr);
    }
}


///

把流转换成字符转

/

package com.example.myapplication.User;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2017/10/12 0012.
 */

public class ToStrring {

    public static String gai(InputStream input, String s){

        StringBuilder builder=new StringBuilder();

        BufferedReader  br=new BufferedReader(new InputStreamReader(input));


        String con;

        try {
            while((con=br.readLine())!=null){
                builder.append(con);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值