Obtains data from the network, parses the output.

Source: Internet
Author: User

What we want to do is get the data from the network and show it in the activity.

First we will import the Gson package, which is the function of converting the JSON string into an equal Java object. The method of obtaining data from the network and saving the data is written into class, which is convenient for later invocation.

import Java.io.BufferedReader; Getting data from the network
import java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import Java.net.URL;

/**
* Created by Administrator on 2016/8/17.
*/
Public class Httputil {
Public static string HttpGet (String params) {
{
httpurlconnection Con=null; // HttpURLConnection How to get Data

InputStream is = null; //input stream
BufferedReader Reader=null; //wrapper character stream into cache, optimizer
StringBuffer sbf=new StringBuffer (); // A string variable whose object can be expanded and modified.
try {
URL url=new url (params); params as URL
con = (httpurlconnection) url.openconnection ();
Con.setconnecttimeout (5 * +);
con.setreadtimeout (5*1000);
con.setrequestproperty ("ApiKey", "5B46143955A4B1FF1B470A94315625CD");
Con.connect ();
if (Con.getresponsecode () ==200) {
is = Con.getinputstream ();
reader=new BufferedReader (New InputStreamReader (IS));
String strread=null;
While ((Strread=reader.readline ())!=null) {
sbf.append (strread);
sbf.append ("\ r \ n");
}
reader.close ();
return sbf.tostring ();
}
} catch (Malformedurlexception e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace ();
}finally {
if (is!= null) {
try {
is.close ();
} catch (IOException e) {
e.printstacktrace ();
}
}
if (con!=null) {
Con.disconnect ();
}
}
return "";

}


}
}



Public class Urlutil {
//Get the network interface of the channel
Public static String channelurl= "Http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";
/ * Access to the network interface for Channel News
/Get Request Parameters
Channelid: news Channel ID, must match exact
ChannelName: news channel name, can be fuzzy matching
Title : News headlines, fuzzy matching
page:: pages
needcontent: need to return body 1 required
needhtml: Whether you need to return the HTML format of body 1 required
*/
Public static String newsurl= "Http://apis.baidu.com/showapi_open_bus/channel_news/search_news";
}
Code in the activity
import Android.os.AsyncTask;
import Android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import Android.view.View;
import Android.widget.AdapterView;
import Android.widget.SimpleAdapter;
import Android.widget.Spinner;
import Android.widget.TextView;
import Android.widget.Toast;

import COM.EXAMPLE.ADMINISTRATOR.JREDUCH07.R;

import Org.json.JSONArray;
import org.json.JSONException;
import Org.json.JSONObject;

import java.util.ArrayList;
import Java.util.HashMap;
import java.util.List;
import Java.util.Map;

Public class Apiactivity extends Appcompatactivity {
private TextView TextView; //For displaying data
private Spinner channel; //drop-down list
private Simpleadapter sa; //Adapter
private list<map<string,string>> channellist; //fan type is stored in the Map,map is two string type of data

@Override
protected void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (R.LAYOUT.ACTIVITY_API);
textview= (TextView) Findviewbyid (R.id.textview);
channel= (Spinner) Findviewbyid (r.id.channel);
channellist=new arraylist<> ();
sa=new simpleadapter (this,channellist,
Android. R.layout.simple_spinner_item,
new string[]{"name"},new int[] {Android. R.ID.TEXT1});
Channel.setadapter (SA);
new Getchanel (). Execute ();
Channel.setonitemselectedlistener (New Adapterview.onitemselectedlistener () {
@Override
Public void onitemselected (adapterview<?> parent, view view, int position, long id) {
map<string,string> map= channellist.get (position);
String channelname= map.get ("name");
String Channelid=map.get (channelname);
String Url=urlutil.newsurl
+ "? channelid="
+channelid+ "&channelname=" +channelname;
new Getnews (). Execute (URL);
}

@Override
Public void onnothingselected (adapterview<?> parent) {

}
});


}


//Get channel
Public class Getchanel extends asynctask<void,void,string>{
@Override
protected String doinbackground (Void ... params) {
return Httputil.httpget (urlutil.channelurl);
}
@Override
protected void OnPostExecute (String s) {
Super.onpostexecute (s);
if (S.equals ("")) {
Toast.maketext (Getbasecontext (), "No Data", Toast.length_short). Show ();
}
try {
Jsonobject obj=new Jsonobject (s);
jsonobject body=obj.getjsonobject ("Showapi_res_body");
Jsonarray Ja=body.getjsonarray ("channellist");
for (int i=0;i<ja.length (); i++) {
jsonobject channelobj= (jsonobject) ja.get (i);
String id=channelobj.getstring ("Channelid");
String name=channelobj.getstring ("name");
Map map=new HashMap ();
map.put ("name", name);
Map.put (name,id);
channellist.add (map);
}
sa.notifydatasetchanged ();

} catch (Jsonexception e) {
e.printstacktrace ();
}
}
}

//Get news
Public class Getnews extends asynctask<string,void,string>{
@Override
protected string Doinbackground (String ... params) {
return Httputil.httpget (Params[0]);
}

@Override
protected void OnPostExecute (String s) {
Super.onpostexecute (s);
if (S.equals ("")) {
Textview.settext ("no");
}
Textview.settext (s);
}
}

}

Obtains data from the network, parses the output.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.