Android中的网络请求之HttpURLConnection

HttpURLConnection简介

HttpURLConnection是URLConnection的子类,每个HttpURLConnection 实例都可用于生成单个请求

HttpURLConnection请求的两种方式及步骤

网络请求数据步骤如下(Get请求)
1.根据url创建URL对象
2.打开连接,获得HttpUrlConnction对象
3.获取响应码(getResponseCode)
4.得到结果的输入流(getInputStream)

网络请求数据步骤如下(post请求)
1.根据url创建URL对象
2.打开连接,获得HttpUrlConnction对象
3.设置请求方式为post
4.设置要向服务器写入数据(conn.setDoOutput(true))
5获得输出流将参数信息写进去
6.获取响应码(getResponseCode)
7.得到响应输入流(getInputStream)

如下代码实现使用HttpUrlConnction的post的方法从http://v.juhe.cn/toutiao/index接口中获取数据并解析输出,显示在listview控件上

/**
* HttpURLConnection 执行post请求的案例
* @author e531
*
*/
public class MainActivity extends Activity {

private Handler myHandler=new Handler(){
    public void handleMessage(android.os.Message msg) {

        List<News> lists=(List<News>)msg.obj;

        //设置适配器,显示
        //.......

    };
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void requestNews(View v){
    new Thread(){
        public void run() {
            //注意:进行post请求时,请求的地址是不包含 参数信息的(?...)
            String path="http://v.juhe.cn/toutiao/index";

            try {
                //1.创建一个URL
                URL url=new URL(path);

                //2.打开连接
                HttpURLConnection openConnection =(HttpURLConnection) url.openConnection();

                //3.设置一些设置
                openConnection.setRequestMethod("POST");//post必须要大写
                openConnection.setReadTimeout(3000);
                openConnection.setConnectTimeout(3000);


                //4.设置输出参数
                openConnection.setDoOutput(true);

                //请求的参数
                String params="type=keji&key=c4479ad58f41e7f78a8fa073d0b1f1b5";
                openConnection.getOutputStream().write(params.getBytes());


                //5.得到响应码
                int code=openConnection.getResponseCode();
                if(code==200){
                    //6.得到结果
                    InputStream inputStream = openConnection.getInputStream();

                    //结果
                    String content=streamToString(inputStream);
                    Log.d("zzz", content);

                    //进行解析
                    Gson gs=new Gson();
                    Result result=gs.fromJson(content, Result.class);
                    Log.d("zzz", result.toString());

                    //新闻列表数据
                    List<News> datas = result.getResult().getData();
            //发送消息
                    Message msg=Message.obtain();
                    msg.obj=datas;
                    myHandler.sendMessage(msg);
    }
} catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

};
    }.start();
}

/**
 * 将字节流信息的内容读取出来
 * @param is
 * @return
 */
public String streamToString(InputStream is){
    StringBuilder builder=new StringBuilder();

    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
    String con;
    try {
        while((con=reader.readLine())!=null){
            builder.append(con);
        }
        reader.close();


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return builder.toString();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值