android 與伺服器用 http Post方法通迅

來源:互聯網
上載者:User

1、android與本機伺服器(同一台電腦)通迅,必須為電腦添加一個IP:  10.0.0.2,否則無法串連上本機伺服器。

 

2、伺服器接收端

     

     這裡就不寫了 直接在model裡面設定要獲到的屬性名稱字就行,如要接收 title,就直接用this.model.getTitle();

 

3、用戶端(發送端)

   public void httpPost2()<br />{<br />try<br />{<br />show.setText(" post2 "+new Date().toString());<br />// http地址<br />String httpUrl = "http://10.0.0.2/wap/doAddNews.action";<br />//HttpPost連線物件<br />HttpPost httpRequest = new HttpPost(httpUrl);<br />//使用NameValuePair來儲存要傳遞的Post參數<br />List<NameValuePair> params = new ArrayList<NameValuePair>();<br />//添加要傳遞的參數<br />params.add(new BasicNameValuePair("title", " 中文哦HttpClient_android_Post"));<br />//設定字元集<br />HttpEntity httpentity = new UrlEncodedFormEntity(params, "UTF-8");<br />//請求httpRequest<br />httpRequest.setEntity(httpentity);<br />//取得預設的HttpClient<br />HttpClient httpclient = new DefaultHttpClient();<br />//取得HttpResponse<br />HttpResponse httpResponse = httpclient.execute(httpRequest);<br />//HttpStatus.SC_OK表示串連成功<br />if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)<br />{<br />//取得返回的字串<br />String strResult = EntityUtils.toString(httpResponse.getEntity());<br />//show.setText(strResult);<br />System.out.println("返回結果:/r/n"+strResult);<br />}<br />else<br />{<br />show.setText("請求錯誤!");<br />}<br />}catch(Exception ex)<br />{<br />System.out.println(ex.toString());<br />}<br />} 

 

    

 

注意:用戶端和服務端使用的都是 UTF-8, 按道理講 用GB2312也行,

不過用戶端的字元編碼和伺服器使用的字元編碼必須一致,

否則,有可能出現亂碼。

   

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.