现在的位置: 首页 > 综合 > 正文

Consuming XML and JSON web services (MyMoviesWithHttpClient)

2017年12月24日 ⁄ 综合 ⁄ 共 5130字 ⁄ 字号 评论关闭

A web service is a set of server-side interfaces exposed on the Internet using web technologies such as HTTP for data transfer or XML and JSON for data serialization. Unlike web sites, web services are meant to be consumed by machines, not human beings.

communication between a web service and a mobile client.

how to consume XML and JSON responses coming from a web service?

XML parsers:two different ways of parsing XML: SAX  and XmlPull.

buffers the document in memory:lightweight approach:JSON.

the MyMovies application: long pressing a list element will now fetch live data in form of a movie rating from the TMDb (The Movie Database) web service.

1.We added a Movie class (a POJO with ID, title,and rating fields).

2.We changed the list adapter to manage Movie objects, not strings (we changed its type from ArrayAdapter<String> to ArrayAdapter<Movie>).

3.We added the OnItemLongClickListener interface to the MyMovies activity where we start a new AsyncTask that will communicate with the TMDb web service.

GetMovieRatingTask retrieves a movies’s IMDb rating from a Web service:


//This task resolves a movie’s IMDb ID (passed as a String) to a Movie object
public class GetMovieRatingTask extends AsyncTask<String,Void,Movie> {
	   private static final String API_KEY = "624645327f33f7866355b7b728f9cd98";
	   private static final String API_ENDPOINT = "http://api.themoviedb.org/2.1";
	   private static final int PARSER_KIND_SAX = 0;
	   private static final int PARSER_KIND_XMLPULL = 1;
	   private static final int PARSER_KIND_JSON = 2;
	   private int parserKind = PARSER_KIND_SAX;
	   private Activity activity;
	   public GetMovieRatingTask(Activity activity){
		   this.activity=activity;
	   }
	   
	@Override
	protected Movie doInBackground(String... params) {
		// TODO Auto-generated method stub
		try{
			//input:IMDb ID;output:movie object
			String imdbId=params[0];
			HttpClient httpClient=MyMovies.getHttpClient();
			String format=parserKind==PARSER_KIND_JSON?"json":"Xml";
			//movie address
			//language (/en) and the response format (/xml).
			//API key, which identifies our application on the web service
			//API key is shared among all users of the application
			String path= "/Movie.imdbLookup/en/" + format + "/" + API_KEY + "/"+ imdbId;
			HttpGet request=new HttpGet(API_ENDPOINT+path);
			//send service request
			HttpResponse response=httpClient.execute(request);
			InputStream data=response.getEntity().getContent();
			//parse response
			switch(parserKind){
			case PARSER_KIND_SAX:
				 return SAXMovieParser.parseMovie(data);
			case PARSER_KIND_XMLPULL:
				 return XmlPullMovieParser.parseMovie(data);
			case PARSER_KIND_JSON:
				 return JsonMovieParser.parseMovie(data);
			default:
				throw new RuntimeException("unsupported parser");
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	//If parsing succeeded, we read the relevant fields from the Movie object 
	//and show them in a pop-up dialog
	protected void onPostExecute(Movie movie){
	if(movie==null){
		Toast.makeText(activity, "Error", Toast.LENGTH_SHORT).show();
		return;
	}
	Dialog dialog=new Dialog(activity);
	dialog.setContentView(R.layout.movie_dialog);
	dialog.setTitle("IMDb rating for \"" + movie.getTitle() + "\"");
	TextView rating=(TextView)dialog.findViewById(R.id.movie_dialog_rating);
	rating.setText(movie.getRating());
	dialog.show();
	}
}

Movie.java

public class Movie {
	private String id,title,rating;
	
	public String toString(){
		return title;
	}
	
	public static List<Movie> inflateFromXml(Context context){
		String[] ids=context.getResources().getStringArray(R.array.movie_ids);
		String[] titles=context.getResources().getStringArray(R.array.movies);
		ArrayList<Movie> movies=new ArrayList<Movie>(ids.length);
		for(int i=0;i<ids.length;i++){
			Movie movie=new Movie();
			movie.setId(ids[i]);
			movie.setTitle(titles[i]);
			movies.add(movie);
		}
		return movies;
	}
	 public String getId() {
	      return id;
	   }

	   public void setId(String id) {
	      this.id = id;
	   }

	   public String getTitle() {
	      return title;
	   }

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

	   public String getRating() {
	      return rating;
	   }

	   public void setRating(String rating) {
	      this.rating = rating;
	   }
}

MovieAdapter.java

public class MovieAdapter extends ArrayAdapter<Movie> {
	private HashMap<Integer,Boolean> movieCollection=new HashMap<Integer,Boolean>();
	private String[] moiveIconUrls;
	
	public MovieAdapter(Context context) {
		//super(context,R.layout.movie_item,android.R.id.text1,context.getResources().getStringArray(R.array.movies));
		super(context,R.layout.movie_item,android.R.id.text1,Movie.inflateFromXml(context));
		// TODO Auto-generated constructor stub
		moiveIconUrls=context.getResources().getStringArray(R.array.movie_thumbs);
	}
	

MyMovies.java

public class MyMovies extends ListActivity implements Callback,OnItemLongClickListener {

@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Getting details...", Toast.LENGTH_LONG).show();
		Movie movie=adapter.getItem(position);
		new GetMovieRatingTask(this).execute(movie.getId());
		return false;
	}

add layout file:movie_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView android:id="@+id/movie_dialog_rating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="45sp"
        android:textStyle="bold"
        />
</LinearLayout>

add array value:movie_ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string-array name="movie_ids">
    <item>tt0111161</item>
    <item>tt0068646</item>
	......
    <item>tt0071562</item>
  </string-array>
</resources>

抱歉!评论已关闭.