【Android】Web開發之通過Apache接口處理Http請求

處理GET請求核心代碼

HttpClient client = new DefaultHttpClient();
HttpGet request= new HttpGet("http://xxx/index.jsp");

HttpResponse response = client.execute(request);

StringBuilder builder = new StringBuilder(“”);
if (response.getStatusLine().getStatusCode() == 500) {

	BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	for (String s = reader.readLine(); s != null; s = reader.readLine())  {
		builder.append(s);
	}

}

處理POST請求核心代碼

HttpClient client = new DefaultHttpClient();
HttpPost request= new HttpPost("http://xxx/index.jsp");

List <NameValuePair> params = new ArrayList <NameValuePair>();    
params.add(new BasicNameValuePair("u", "沈大海"));    
params.add(new BasicNameValuePair("p", "123"));

/* 添加請求參數到請求對象*/  
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = client.execute(request); 

if (response.getStatusLine().getStatusCode() == 200) {
	 String strResult = EntityUtils.toString(httpResponse.getEntity());    
}

處理GET請求方法

發送GET請求並獲取服務器端返回值:
	public String handleGet(String strUrl) {
		StringBuffer buffer = null;
		HttpGet request = new HttpGet(strUrl);//實例化一個HttpGet請求(指定URL)
		DefaultHttpClient client = new DefaultHttpClient();//實例化一個客戶端
		try {
			HttpResponse response = client.execute(request);//調用客戶端的execute(request)執行請求
			//獲取服務器端返回的狀態碼是否等於200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());//調用getEntity獲取返回值,需通過EntityUtils把實體轉成String
			} else {
				result = response.getStatusLine().toString();
			}
		} catch (Exception e) { }
		return result;
	}


處理POST請求方法

攜帶一個params數據發送Post請求到指Url:
	public String handlePost(String strUrl, List<NameValuePair> params) {
		HttpPost request = new HttpPost(strUrl);//建立HTTPPost對象
		try {
			//設置該請求要攜帶的參數
			request.setEntity(new UrlEncodedFormEntity(params, "GBK"));
			HttpResponse response = new DefaultHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity());
			} else {
				result = response.getStatusLine().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

應用實例

爲了更加清晰的理解上述兩個方法,可通過下述實例進行練習。
【注】服務請求是應該寫在Handler中,配合線程一起使用的,在這裏爲了測試簡便而暫不使用。

Activity

package com.app.myweb;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * 範例:通過Apache接口處理Http請求
 */
public class ApacheHttp_JSP extends Activity implements OnClickListener {
	
	private TextView textView1, textView2, textView3;
	private Button button1, button2;
	private StringBuffer sb;
	private String result;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http_jsp);

		setUI(); setAction();
	}

	public void setUI() {
		/*
		 * textView1 = (TextView) findViewById(R.id.textView1);
		 * textView1.setText("利用Java標準接口java.net.*類實現讀取指定url內容");
		 */
		textView3 = (TextView) findViewById(R.id.textView3);

		button1 = (Button) findViewById(R.id.button1);
		button2 = (Button) findViewById(R.id.button2);
		button1.setText("Apache接口:發送GET請求");
		button2.setText("Apache接口:發送POST請求");
	}

	public void setAction() {
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.button2).setOnClickListener(this);
	}

	/** 發送GET請求並獲取服務器端返回值 */
	public String handleGet(String strUrl) {
		StringBuffer buffer = null;
		HttpGet request = new HttpGet(strUrl);//實例化一個HttpGet請求(指定URL)
		DefaultHttpClient client = new DefaultHttpClient();//實例化一個客戶端
		try {
			HttpResponse response = client.execute(request);//調用客戶端的execute(request)執行請求
			//獲取服務器端返回的狀態碼是否等於200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());//調用getEntity獲取返回值,需通過EntityUtils把實體轉成String
			} else {
				result = response.getStatusLine().toString();
			}
		} catch (Exception e) { }
		return result;
	}
	
	/** 攜帶一個params數據發送Post請求到指Url */
	public String handlePost(String strUrl, List<NameValuePair> params) {
		HttpPost request = new HttpPost(strUrl);//建立HTTPPost對象
		try {
			//設置該請求要攜帶的參數
			request.setEntity(new UrlEncodedFormEntity(params, "GBK"));
			HttpResponse response = new DefaultHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity());
			} else {
				result = response.getStatusLine().toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.button1:
			textView3.setText(handleGet("http://10.0.2.2:8888/android/1.jsp"));
			break;
		case R.id.button2:
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", "tom"));
			params.add(new BasicNameValuePair("password", "1"));
			textView3.setText(handlePost("http://10.0.2.2:8888/android/2.jsp", params));
			break;
		default:
			break;
		}
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章