Android http get/post傳遞參數

來源:互聯網
上載者:User

    本程式介紹如何通過HttpClient模組來建立Http串連,並分別以Http Get和Post方法傳遞參數,串連之後取回web server的返回網頁結果。

     注意,在用Post時,傳遞變數必須用NameValuePais[]數組儲存,通過HttpRequest.setEntity()方法來發出http請求。

     此外,也必須通過DefaultHttpClient().execute(httpRequest)添加HttpRequest對象來接收web server的回複,在通過httpResponse.getEntity()取出回複資訊。

/*必需引用apache.http相關類別來建立HTTP聯機*/<br />import org.apache.http.HttpResponse;<br />import org.apache.http.NameValuePair;<br />import org.apache.http.client.ClientProtocolException;<br />import org.apache.http.client.entity.UrlEncodedFormEntity;<br />import org.apache.http.client.methods.HttpGet;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.message.BasicNameValuePair;<br />import org.apache.http.protocol.HTTP;<br />import org.apache.http.util.EntityUtils;<br />/*必需引用java.io 與java.util相關類來讀寫檔案*/<br />import java.io.IOException;<br />import java.util.ArrayList;<br />import java.util.List;<br />import java.util.regex.Matcher;<br />import java.util.regex.Pattern;</p><p>import android.app.Activity;<br />import android.os.Bundle;<br />import android.view.View;<br />import android.widget.Button;<br />import android.widget.TextView; </p><p>public class EX08_01 extends Activity<br />{<br /> /*聲明兩個Button對象,與一個TextView對象*/<br /> private Button mButton1,mButton2;<br /> private TextView mTextView1; </p><p> /** Called when the activity is first created. */<br /> @Override<br /> public void onCreate(Bundle savedInstanceState)<br /> {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main); </p><p> /*透過findViewById建構子建立TextView與Button對象*/<br /> mButton1 =(Button) findViewById(R.id.myButton1);<br /> mButton2 =(Button) findViewById(R.id.myButton2);<br /> mTextView1 = (TextView) findViewById(R.id.myTextView1); </p><p> /*設定OnClickListener來聆聽OnClick事件*/<br /> mButton1.setOnClickListener(new Button.OnClickListener()<br /> {<br /> /*重寫onClick事件*/<br /> @Override<br /> public void onClick(View v)<br /> {<br /> /*聲明網址字串*/<br /> String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Post/index.php";<br /> /*建立HTTP Post聯機*/<br /> HttpPost httpRequest = new HttpPost(uriAPI);<br /> /*<br /> * Post運作傳送變數必須用NameValuePair[]數組儲存<br /> */<br /> List <NameValuePair> params = new ArrayList <NameValuePair>();<br /> params.add(new BasicNameValuePair("str", "I am Post String"));<br /> try<br /> {<br /> /*發出HTTP request*/<br /> httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));<br /> /*取得HTTP response*/<br /> HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);<br /> /*若狀態代碼為200 ok*/<br /> if(httpResponse.getStatusLine().getStatusCode() == 200)<br /> {<br /> /*取出響應字串*/<br /> String strResult = EntityUtils.toString(httpResponse.getEntity());<br /> mTextView1.setText(strResult);<br /> }<br /> else<br /> {<br /> mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());<br /> }<br /> }<br /> catch (ClientProtocolException e)<br /> {<br /> mTextView1.setText(e.getMessage().toString());<br /> e.printStackTrace();<br /> }<br /> catch (IOException e)<br /> {<br /> mTextView1.setText(e.getMessage().toString());<br /> e.printStackTrace();<br /> }<br /> catch (Exception e)<br /> {<br /> mTextView1.setText(e.getMessage().toString());<br /> e.printStackTrace();<br /> } </p><p> }<br /> });<br /> mButton2.setOnClickListener(new Button.OnClickListener()<br /> {<br /> @Override<br /> public void onClick(View v)<br /> {<br /> // TODO Auto-generated method stub<br /> /*聲明網址字串*/<br /> String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Get/index.php?str=I+am+Get+String";<br /> /*建立HTTP Get聯機*/<br /> HttpGet httpRequest = new HttpGet(uriAPI);<br /> try<br /> {<br /> /*發出HTTP request*/<br /> HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);<br /> /*若狀態代碼為200 ok*/<br /> if(httpResponse.getStatusLine().getStatusCode() == 200)<br /> {<br /> /*取出響應字串*/<br /> String strResult = EntityUtils.toString(httpResponse.getEntity());<br /> /*刪除多餘字元*/<br /> strResult = eregi_replace("(/r/n|/r|/n|/n/r)","",strResult);<br /> mTextView1.setText(strResult);<br /> }<br /> else<br /> {<br /> mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());<br /> }<br /> }<br /> catch (ClientProtocolException e)<br /> {<br /> mTextView1.setText(e.getMessage().toString());<br /> e.printStackTrace();<br /> }<br /> catch (IOException e)<br /> {<br /> mTextView1.setText(e.getMessage().toString());<br /> e.printStackTrace();<br /> }<br /> catch (Exception e)<br /> {<br /> mTextView1.setText(e.getMessage().toString());<br /> e.printStackTrace();<br /> }<br /> }<br /> });<br /> }<br /> /* 自訂字串取代函數 */<br /> public String eregi_replace(String strFrom, String strTo, String strTarget)<br /> {<br /> String strPattern = "(?i)"+strFrom;<br /> Pattern p = Pattern.compile(strPattern);<br /> Matcher m = p.matcher(strTarget);<br /> if(m.find())<br /> {<br /> return strTarget.replaceAll(strFrom, strTo);<br /> }<br /> else<br /> {<br /> return strTarget;<br /> }<br /> }<br />} </p><p>  

在androidManifest.xml中必須添加許可權:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.