I heard that the volley framework is very useful, today tried a POST request, it is true, because I passed the JSON is also json to write a request for JSON, in fact, the other code is similar. First create a global variable, the request into the queue using the following code:
public class MyApplication extends application{
public static Requestqueue Requestqueue;
public static context context;
@Override
public void OnCreate () {
TODO auto-generated Method Stub
Super.oncreate ();
Requestqueue=volley.newrequestqueue (Getapplicationcontext ());
}
public static Requestqueue Gethttprequestqueue () {
return requestqueue;
}
}
Then start the request code as follows:
public class Volley {
Public String url= "Http://api.avatardata.cn/Joke/NewstJoke";
String ResultStr;
Gson Gson;
Public Volley () {
Volleypost ();
}
public void Volleypost () {
Stringrequest request=new stringrequest (method.post,url,new listener<string> () {
@Override
public void Onresponse (String response) {
TODO auto-generated Method Stub
System.out.println (Response.tostring ());
Resultstr=response.tostring ();
Gson gson=new Gson ();
Idiom Idiom=gson.fromjson (ResultStr, Idiom.class);
System.out.println (idiom);
}
}, New Errorlistener () {
@Override
public void Onerrorresponse (Volleyerror error) {
TODO auto-generated Method Stub
System.out.println (Error.tostring ());
Resultstr=error.tostring ();
}
}){
@Override
Protected Map<string, string> Getparams () throws Authfailureerror {
TODO auto-generated Method Stub
Map<string,string> map=new hashmap<string, string> ();
Map.put ("Key", "Yourkey");
Map.put ("Dtype", "JSON");
Map.put ("format", "true");
Map.put ("page", "1");
Map.put ("Rows", "10");
return map;
}
};
Myapplication.gethttprequestqueue (). Add (Request);
}
}
This makes it easy to get JSON data. How else to get the data to parse it? The simple JSON we directly with the android inside Jsonobject can solve, but a little more complex, including the array what the words will be very troublesome, it does not matter, can be used to Gson JSON parsing, is to get JSON string field all encapsulated into the object, encountered [ ] Just use list, encounter {} with object to define, layer of encapsulation, and then instantiate Gson, can easily get to the data.
The following string, truncation is incomplete:
OK, that's it, you can call me if you need the code. Because I am lazy, so everyone will point it, although you can not see the detailed code, but the method is very clear understanding.
The two classes I've encapsulated.
Use of Android Volley+gson