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

HTTP with Apache HttpClient_(MyMoviesWithHttpClient)

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

The Apache HTTP Components are composed of two parts: HttpCore, a set of lowlevel classes for handling HTTP connections, and HttpClient, a more high-level set of

classes built on top of HttpCore, which is used to implement typical HTTP user agent software (any applications that connect to a web server).

You’re implementing an HTTP user agent, such as a web service consumer, and you want a fully featured, powerful, yet easy-to-use solution to handle the HTTP communication with the server.

Communication with an HTTP server via Apache HttpClient typically involves five different interfaces that are fundamental to request execution so you will deal with
them frequently. These are HttpRequest (and its implementations HttpGet, Http-Post, and so forth) for configuring requests, HttpClient for sending requests, HttpResponse for processing a server response, HttpContext to maintain state of the communication, and
HttpEntity, which represents the payload that’s sent with a request or response.

Typically you have one HttpClient object per application (it makes sense to encapsulate it in your Application class or maintain it as a static field), one HttpContext object per request-response group, and one Http- Request and HttpResponse respectively
per request you make.

but don’t confuse it with traditional HTTP sessions (often implemented via HTTP cookies). HttpContext is a mere client-side execution context; think of it as attributes you can maintain and track across several requests. If you don’t know what this is useful
for then chances are you won’t need it. In fact, because most people don’t need it, the default execute method of HttpClient will create and maintain an execution context for you, so you can ignore it. For these reasons, we won’t mention HttpContext again.

UpdateNoticeTask.java

public class UpdateNoticeTask extends AsyncTask<Void,Void,String> {
	private static final String UPDATE_URL =
        "http://android-in-practice.googlecode.com/files/update_notice.txt";
	private HttpURLConnection connection;
	private Handler handler;
	public UpdateNoticeTask(Handler handler){
		this.handler=handler;
	}
	
	@Override
	protected String doInBackground(Void... params) {
		// TODO Auto-generated method stub
		try{
			//get Requset from URL
			 HttpGet request=new HttpGet(UPDATE_URL);
			 //configure requset header
			 request.setHeader("Accept","text/plain");
			 //from the main activity using a static getter
			 //execute:open the connection and send the request using a 
			 //default HttpContext
			 HttpResponse response=MyMovies.getHttpClient().execute(request);
			 int statusCode=response.getStatusLine().getStatusCode();
			 if(statusCode!=HttpStatus.SC_OK)
				 return "Error:Failed getting update notes";
			 //read response into string
			 //read from inputstream into string
			 return EntityUtils.toString(response.getEntity());
		}catch(Exception e){
			return "Error:"+e.getMessage();
		}
//		try{
//			URL url=new URL(UPDATE_URL);
//			//get instance of HttpURLConnection
//			connection=(HttpURLConnection)url.openConnection();
//			//configure request
//			connection.setRequestMethod("GET");
//			connection.setRequestProperty("Accept", "text/plain");
//			connection.setReadTimeout(10);
//			connection.setConnectTimeout(10);
//			//establish connection
//			connection.connect();
//			int statusCode=connection.getResponseCode();
//			if(statusCode!=HttpURLConnection.HTTP_OK)
//				//handl non-200 reply
//				return "error: Failed getting update notes";
//			return readTextFromServer();//reand text from response
//		}catch(Exception e){
//			return "Error: " + e.getMessage();
//		}finally{
//			if(connection!=null)
//				//close connection
//				connection.disconnect();
//		}
	}
	
	private String readTextFromServer() throws IOException{
		InputStreamReader isr=new InputStreamReader(connection.getInputStream());
		BufferedReader br=new BufferedReader(isr);
		StringBuilder sb=new StringBuilder();
		String line=br.readLine();
		while(line!=null){
			sb.append(line+"\n");
			line=br.readLine();
		}
		return sb.toString();
		
	}
	//pass retrive text to activity
	protected void onPostExecute(String updateNotice){
		Message message=new Message();
		Bundle data=new Bundle();
		data.putString("text", updateNotice);
		message.setData(data);
		handler.sendMessage(message);
	}
}

MyMovies.java

public class MyMovies extends ListActivity implements Callback {
	private static final AbstractHttpClient httpClient;
	private MovieAdapter adapter;
	static{
		httpClient=new DefaultHttpClient();
	}
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		ListView listView=getListView();
		
		Button backToTop=(Button)getLayoutInflater().inflate(R.layout.list_footer, null);
		backToTop.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(android.R.drawable.ic_menu_upload),
				null, null, null);
		listView.addFooterView(backToTop);
		
		this.adapter=new MovieAdapter(this);
		listView.setAdapter(adapter);
		listView.setItemsCanFocus(false);
		
		new UpdateNoticeTask(new Handler(this)).execute();//starts new download task
	}
	
    public void backToTop(View view) {
        getListView().setSelection(0);
    }
    
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	this.adapter.toggleMovie(position);
    	this.adapter.notifyDataSetInvalidated();
    }
    
	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		String updateNotice=msg.getData().getString("text");//reads update text
		AlertDialog.Builder dialog=new AlertDialog.Builder(this);
		dialog.setTitle("What's new");
		dialog.setMessage(updateNotice);//set update text
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setPositiveButton(getString(android.R.string.ok), new OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		dialog.show();
		return false;
	}
	
	public static HttpClient getHttpClient(){
		return httpClient;
	}
}

we have separate objects for request and response, we have a client object to send and receive them, and we have the entity object that wraps the message payload. We also have helper classes at our disposal that allow us to instantly process a response by reading
it into a string.a byte array, and so on.

the convention-over-configuration pattern.

it’s slower and has a larger memory footprint, so choose carefully which tasks you want to perform using the swift-but-ugly HttpURLConnection, and which should use the friendly-butheavy Apache HttpClient classes.

The most commonly used one is DefaultHttpClient, which sets a couple of sane defaults for connections based on the HTTP/1.1 protocol version. These include things such as a default HTTP user agent header, a default TCP socket buffer size, a default request-retry
handler that retries sending a request up to three times if it’s safe to do so (if we’re dealing with idempotent requests), and so forth. It also registers a handler for HTTPS (HTTP over SSL) URLs on port 443.

抱歉!评论已关闭.