Package com.example.day_02_httpurlconnection;
Import Java.io.BufferedReader;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.net.URLEncoder;
Import java.util.ArrayList;
Import java.util.List;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.widget.ListView;
Import Android.widget.Toast;
Import Com.example.adapter.MyAdapter;
Import Com.example.vo.Result;
Import Com.example.vo.Root;
Import Com.google.gson.Gson;
public class Mainactivity extends Activity {
Private String Path = "http://op.juhe.cn/onebox/news/query?q= Putin &key=f2219bf102195209a3db41a58ce0b180";
list<result> list = new arraylist<result> ();
Handler Handler = new Handler () {
public void Handlemessage (Message msg) {
Root root = (root) msg.obj;
List.addall (Root.getresult ());
Lv.setadapter (New Myadapter (mainactivity.this,list));
Toast.maketext (Mainactivity.this, List.get (1). GetTitle (), Toast.length_short)
. Show ();
};
};
Private ListView LV;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
LV = (ListView) Findviewbyid (r.id.lv);
New Thread () {
@Override
public void Run () {
GetData ();
}
}.start ();
}
private void GetData () {
try {
String name = Urlencoder.encode ("Putin", "UTF-8");
Set path
URL url = new URL ("http://op.juhe.cn/onebox/news/query?q=" +name+ "&key=f2219bf102195209a3db41a58ce0b180");
Get HttpURLConnection Object
HttpURLConnection httpconnection = (httpurlconnection) URL
. OpenConnection ();
Setting the connection timeout
Httpconnection.setconnecttimeout (5000);
Set Read timeout
Httpconnection.setreadtimeout (5000);
To set the method of the request
Httpconnection.setrequestmethod ("GET");
Start the official networking
Httpconnection.connect ();
Get Status Code
int code = Httpconnection.getresponsecode ();
Determine if the connection is successful
if (code = = 200) {
Get the flow of data
InputStream InputStream = Httpconnection.getinputstream ();
Read content through BufferedReader
BufferedReader BufferedReader = new BufferedReader (
New InputStreamReader (InputStream, "UTF-8"));
String str;
StringBuffer StringBuffer = new StringBuffer ();
reading data by looping
while ((str = bufferedreader.readline ()) = null) {
Stringbuffer.append (str);
}
String data = stringbuffer.tostring ();
SYSTEM.OUT.PRINTLN (data);
Get Gson Object
Gson Gson = new Gson ();
To parse out the resulting data
Root root = Gson.fromjson (data, root.class);
Send data to the main thread
Message msg = Message.obtain ();
Msg.obj = root;
Handler.sendmessage (msg);
} else {
Toast.maketext (Mainactivity.this, "request failed! ", Toast.length_short)
. Show ();
}
} catch (Exception Exception) {
Exception.printstacktrace ();
}
}
}
HttpURLConnection Simple usage