一)HttpGet :doGet()方法 //doGet():將參數的鍵值對附加在url后面來傳遞 public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{ //服務器 :服務器項目 :servlet名稱 String path="http://192.168.5.21:8080/test/test"; String uri=path+"?name="+name+"&pwd="+pwd; //name:服務器端的用戶名,pwd:服務器端的密碼 //注意字符串連接時不能帶空格 String result=""; HttpGet httpGet=new HttpGet(uri); //取得HTTP response HttpResponse response=new DefaultHttpClient().execute(httpGet); //若狀態碼為200 if(response.getStatusLine().getStatusCode()==200){ //取出應答字符串 HttpEntity entity=response.getEntity(); result=EntityUtils.toString(entity, HTTP.UTF_8); } return result; } (二)HttpPost :doPost()方法 //doPost():將參數打包到http報頭中傳遞 public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{ //服務器 :服務器項目 :servlet名稱 String path="http://192.168.5.21:8080/test/test"; HttpPost httpPost=new HttpPost(path); //注意:httpPost方法時,傳遞變量必須用NameValuePair[]數據存儲,通過httpRequest.setEntity()方法來發出HTTP請求 List<NameValuePair>list=new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("name", name)); list.add(new BasicNameValuePair("pwd", pwd)); httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8)); String result=""; //取得HTTP response HttpResponse response=new DefaultHttpClient().execute(httpPost); //若狀態碼為200 if(response.getStatusLine().getStatusCode()==200){ //取出應答字符串 HttpEntity entity=response.getEntity(); result=EntityUtils.toString(entity, HTTP.UTF_8); } return result; }