[Android] HttpUrlConnection the study notes GET

[Overview] The two most common types of network requests: GET and POST. Case GET request using remote data.

Remote Address: http: //www.***.com/data/type=3&cid=1, to get the data as follows:

{"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"}

First, the steps of:

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

step1: instantiate a URL object

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

step2: get httpUrlConnection objects

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

step3: Set connection request properties

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

step4: Get response code, determines whether the connection is successful

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

step5: takes an input stream and parses

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");

Second, the problem arises

① http request can not be initiated in the main thread

Solution: Create a new thread

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

The request code into the run, the code is as follows:

 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();

Parsing the data ②JSON

It is noted that the object is determined String int or Jsonobject, corresponding to the application method to resolve.

//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);

③ child thread can not modify the main thread control content

nameView.setText(title)

When the main thread textView perform the modification of data in the child thread, the following error


Find 73f, the code is:

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

This is because the changes to the content control textView the main thread to create a child thread and error.

Solution: The operation been transferred to the main thread, and the other to create a class: Eesay, the following code

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;
    }
}
In the new thread will add the following code to transmit the operation right main thread
//将操作权交还给主线程
                        Eesay e=new Eesay(title,author,content);
                        Message message=handler.obtainMessage();
                        message.obj=e;
                        //调用此方法则会触发主线程中handler对象下覆盖的HandlerMessage方法
                        handler.sendMessage(message);
Use 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());
        }
    };



Published 44 original articles · won praise 21 · views 30000 +

Guess you like

Origin blog.csdn.net/gzyh_tech/article/details/80809616