1. 程式人生 > >Android請求java端通用類

Android請求java端通用類

/**
 * 封裝 HttpClient物件POST請求
 * 
 */
public class HttpClientPost implements Serializable {

	private static final long serialVersionUID = 1777547416049652217L;

	private static HttpClient httpClient = new DefaultHttpClient();

	static {
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 連線時間
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				3000);// 資料傳輸時間
	}

	// 字符集
	private static String encoding = "UTF-8";

	// 伺服器地址+埠號+專案名
	private static String basePath = "http://192.168.43.92:8080/news";

	// 子控制器的路徑
	private String path;

	// 儲存請求中的引數
	private List<NameValuePair> params = new ArrayList<NameValuePair>();;

	public HttpClientPost(String path) {
		super();
		this.path = path;
	}

	/**
	 * 向POST請求中新增引數
	 * 
	 * @param name
	 * @param value
	 */
	public void addParam(String name, String value) {
		if (value == null) {
			params.add(new BasicNameValuePair(name, ""));
		} else {
			params.add(new BasicNameValuePair(name, value));
		}
	}

	/**
	 * 提交POST請求
	 */
	@SuppressWarnings("unchecked")
	public void submit(final HttpClientPost.Callback callback) {
		new AsyncTask() {
			private String json;

			@Override
			protected Object doInBackground(Object... args) {
				try {
					// 1. 建立HttpClient物件

					// 2. 建立HttpGet(或HttpPost)物件
					HttpPost httpPost = new HttpPost(basePath + path);

					// 3. 向POST請求中新增引數(可選)
					if (0 != params.size()) {
						HttpEntity paramEntity = new UrlEncodedFormEntity(
								params, encoding);
						httpPost.setEntity(paramEntity);
					}

					// 4. 傳送POST請求,並獲得響應
					HttpResponse httpResponse = httpClient.execute(httpPost);

					// 5. 處理響應
					if (200 == httpResponse.getStatusLine().getStatusCode()) {
						HttpEntity responseEntity = httpResponse.getEntity();// 此物件包含伺服器的響應內容
						this.json = EntityUtils.toString(responseEntity);
					}
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				return null;
			}

			protected void onPostExecute(Object result) {
				callback.execute(this.json);
			}

		}.execute();
	}

	public static interface Callback {
		void execute(String json);
	}
}

 HttpClient的使用步驟
  3.1 建立HttpClient物件
      HttpClient httpClient = new DefaultHttpClient();

  3.2 建立HttpGet(或HttpPost)物件
      HttpGet HttpGet = new HttpGet("http://www.baidu.com");
      HttpPost httpPost = new HttpPost("http://www.baidu.com");

  3.3 新增引數(可選)
      setParams(HttpParams params)//HttpGet和HttpPost共有
      setEntity(HttpEntity entity)//HttpPost獨有

      List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("age", "20"));
    params.add(new BasicNameValuePair("like", "aa"));
    params.add(new BasicNameValuePair("like", "bb"));
    params.add(new BasicNameValuePair("like", "cc"));
    params.add(new BasicNameValuePair("newsCategoryId", "1"));
    HttpEntity paramEntity = new UrlEncodedFormEntity(params,"UTF-8");
    httpPost.setEntity(paramEntity);
      
  3.4 傳送GET(或POST)請求,並獲得響應
      HttpResponse httpResponse = httpClient.execute(HttpUriRequest request);
 
      注1:HttpUriRequest為HttpGet和HttpPost的父類
      注2:需要新增允許網路訪問許可權,不然會報錯“java.lang.SecurityException: Permission denied (missing INTERNET permission?)”
           <uses-permission android:name="android.permission.INTERNET" />

      注3:如果地址錯誤,或伺服器未開戶,HttpClient這SB會等待N久(>24小時)。
           所以請記得設定超時時間,所以請記得設定超時時間,所以請記得設定超時時間
           所以請記得設定超時時間,所以請記得設定超時時間,所以請記得設定超時時間
           所以請記得設定超時時間,所以請記得設定超時時間,所以請記得設定超時時間

           另外HttpClient版本不一樣,程式碼也不一樣。下面的4.0版本的寫法
           httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 連線時間
           httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);// 資料傳輸時間

  3.5 處理響應
    3.5.1 響應狀態碼(200)
          httpResponse.getStatusLine().getStatusCode()

    3.5.2 響應頭
          getAllHeaders()/getHeaders(String name)

    3.5.3 響應內容
          HttpEntity httpEntity = httpResponse.getEntity();//此物件包含伺服器的響應內容
          String result = EntityUtils.toString(httpEntity);

bug

//匯入httpclient
useLibrary 'org.apache.http.legacy'


//匯入jackson
packagingOptions {  
        exclude 'META-INF/DEPENDENCIES'  
        exclude 'META-INF/LICENSE'  
        exclude 'META-INF/LICENSE.txt'  
        exclude 'META-INF/license.txt'  
        exclude 'META-INF/NOTICE'  
        exclude 'META-INF/NOTICE.txt'  
        exclude 'META-INF/notice.txt'  
        exclude 'META-INF/ASL2.0'  
    }