Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 服務器操作類

android 服務器操作類

編輯:關於Android編程

簡單 方便

/**
 * @author think
 *以同步方式發送Http請求
 */

public class ApacheHttpClient {
	
       /**
     * @return 
     * 
     */
    public String httpGet(String uri) {
    	String response=null;//響應 
    	HttpClient httpClient=new DefaultHttpClient();
    	//創建HttpGet對象
    	HttpGet httpGet=new HttpGet(uri);
    	HttpResponse httpResponse;
    	try {
    		//使用execute方法發送HTTP GET請求,並返回HttpResponse對象
			httpResponse=httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();//返回碼 ,
			if (statusCode==HttpStatus.SC_OK) {
				//獲得返回結果
				response=EntityUtils.toString(httpResponse.getEntity());
			}
			else {
				response = "返回碼:"+statusCode;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			      e.printStackTrace();}

    	System.out.println(response);
		  return response;
		
	}
       
    /**
	 * 以Post方式發送請求
	 * @param url 請求地址
	 * @param params 參數 ,Post方式必須用NameValuePair[]陣列儲存參數
	 * @return
	 * @throws Exception
	 */
    public String httpPost(String uri,List params) throws Exception{
    	String response=null;
    	
    	HttpClient httpClient=new DefaultHttpClient();
    	HttpPost httpPost=new HttpPost(uri);
    	try {
    		//設置httpPost請求參數
        	httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
        	//使用execute方法發送HTTP Post請求,並返回HttpResponse對象
        	HttpResponse httpResponse=httpClient.execute(httpPost);
        	int statusCode = httpResponse.getStatusLine().getStatusCode();//返回碼 ,
        	if (statusCode==HttpStatus.SC_OK) {
				response=EntityUtils.toString(httpResponse.getEntity());
				System.out.println("______________"+response);
			}
        	else {
        		response = "返回碼:"+statusCode;
        		System.out.println("______________"+response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return response;
		
	}
}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved