【android学习笔记】HttpUrlConnection之GET

【概述】最常用的两种网络请求类型:GET和POST。案例使用GET请求远程数据。

远程地址:http://www.***.com/data/type=3&cid=1,要获取的数据如下:

{"status":1,"data":{"title":"Tony\u8001\u5e08\u804ashell\u2014\u2014\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6","author":"Tony","content":"\u672c\u8bfe\u7a0b\u662f\u300aTony\u8001\u5e08\u804ashell\u300b\u7cfb\u5217\u8bfe\u7a0b\u7684\u7b2c\u4e09\u7bc7\uff0c\u4e3a\u4f60\u5e26\u6765\u5e38\u7528\u7684\u73af\u5883\u53d8\u91cf\u914d\u7f6e\u6587\u4ef6\u7684\u4f7f\u7528\u3002"},"msg":"\u6210\u529f"}

一、步骤:

//1实例化一个url对象
        //2获取httpUrlConnection对象
        //3设置请求连接属性
        //4获取响应码,判断是否连接成功
        //5读取输入流并解析

step1:实例化一个URL对象

URL url=new URL("http://www.***.com/data/type=3&cid=1");//step1

step2:获取httpUrlConnection对象

HttpURLConnection coon= (HttpURLConnection) url.openConnection();//step2

step3:设置请求连接的属性

coon.setRequestMethod("GET");//step3

step4:获取响应码,判断是否连接成功

if(coon.getResponseCode()==200){.....do something....}

step5:获取输入流并解析

InputStream in=coon.getInputStream();
                        byte[] b=new byte[1024*512];
                        int len=0;
                        //建立缓存流,保存所读取的字节数组
                        ByteArrayOutputStream baos =new ByteArrayOutputStream();
                        while ((len=in.read(b))>-1){

                            baos.write(b,0,len);
                        }
                        String msg=baos.toString();
                        Log.e("TAG",msg);
                        //json数据的解析
                        JSONObject obj=new JSONObject(msg);
                        int status=obj.getInt("status");
                        String msg2=obj.getString("msg");
                        Log.e("TAG",status+"  "+msg2);
                        JSONObject data=obj.getJSONObject("data");
                        String title=data.getString("title");
                        String author=data.getString("author");
                        String content=data.getString("content");

二、出现的问题

①发起的http请求不能在主线程中

解决办法:创建新线程

new Thread(){
            @Override
            public void run() {
                super.run();//△
            }
        }

将请求代码粘贴到run中,代码如下:

 new Thread(){
            @Override
            public void run() {
                try {
                    URL url=new URL("http://www.***.com/data/type=3&cid=1");//step1
                    HttpURLConnection coon= (HttpURLConnection) url.openConnection();//step2
                    coon.setRequestMethod("GET");//step3
                    coon.setReadTimeout(6000);
                    if(coon.getResponseCode()==200){//step4
                        //获取输入流
                        InputStream in=coon.getInputStream();
                        byte[] b=new byte[1024*512];
                        int len=0;
                        //建立缓存流,保存所读取的字节数组
                        ByteArrayOutputStream baos =new ByteArrayOutputStream();
                        while ((len=in.read(b))>-1){

                            baos.write(b,0,len);
                        }
                        String msg=baos.toString();
                        Log.e("TAG",msg);
                        //json数据的解析
                        JSONObject obj=new JSONObject(msg);
                        int status=obj.getInt("status");
                        String msg2=obj.getString("msg");
                        Log.e("TAG",status+"  "+msg2);
                        JSONObject data=obj.getJSONObject("data");
                        String title=data.getString("title");
                        String author=data.getString("author");
                        String content=data.getString("content");
                        Log.e("TAG","标题:"+title+",作者:"+author+",内容:"+content);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();

②JSON数据的解析

应注意判断对象是String int or Jsonobject,应用对应的方法去解析。

//json数据的解析
                        JSONObject obj=new JSONObject(msg);
                        int status=obj.getInt("status");
                        String msg2=obj.getString("msg");
                        Log.e("TAG",status+"  "+msg2);
                        JSONObject data=obj.getJSONObject("data");
                        String title=data.getString("title");
                        String author=data.getString("author");
                        String content=data.getString("content");
                        Log.e("TAG","标题:"+title+",作者:"+author+",内容:"+content);

③子线程不能修改主线程控件内容

nameView.setText(title)

在子线程中执行修改主线程textView的数据时,出现以下报错


找到73f,代码是:

nameView.setText(title);
                        authorView.setText(author);
                        contentView.setText(content);

这是因为子线程中进行了对主线程中创建的控件textView的内容的修改而报错。

解决办法:将操作权转交给主线程,另建立一个class:Eesay,代码如下

public class Eesay {
    private String title;
    private String author;
    private String content;

    public Eesay(String title, String author, String content) {
        this.title = title;
        this.author = author;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
在新线程添加如下代码将操作权转交主线程
//将操作权交还给主线程
                        Eesay e=new Eesay(title,author,content);
                        Message message=handler.obtainMessage();
                        message.obj=e;
                        //调用此方法则会触发主线程中handler对象下覆盖的HandlerMessage方法
                        handler.sendMessage(message);
使用Handler
 private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Eesay e= (Eesay) msg.obj;
            nameView.setText(e.getTitle());
            authorView.setText(e.getAuthor());
            contentView.setText(e.getContent());
        }
    };



发布了44 篇原创文章 · 获赞 21 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/gzyh_tech/article/details/80809616
今日推荐