TShopping
標題:
Android之HttpPost與HttpGet使用
[打印本頁]
作者:
woff
時間:
2016-2-4 14:11
標題:
Android之HttpPost與HttpGet使用
什麼是Get?什麼是Post?
對於寫網頁程式的人來說應該是不陌生,在網頁表單中,要送出資料時就會選擇要用Get的方式還是Post的方式。常見的Get方式是在網址後面加上查詢字串,像是
http://www.myweb.com/product?p=1&a=1&b=2
之類的,第一個用問號(?),之後每個都用(&)。
在Android中一樣可以用Get及Post去取得伺服器給予的資料。
在Android中使用Get及Post的幾個提示
使用org.apache.http套件(也可以用別的)
Androidmanifest.xml中要加入存取網路的授權
清楚知道要使用Get還是Post
如果抓網路資料時間太久,建議把它放到背景執行並加上Loading提示
Get的使用步驟
首頁你要建立一個HttpClient 物件:
HttpClient client = new DefaultHttpClient();
複製代碼
接著建立HttpGet物件並傳入網址:
HttpGet get = new HttpGet(_url);
複製代碼
當HttpClient執行Get任務後,會傳回HttpResponse :
HttpResponse response = client.execute(get);
複製代碼
接下來就可以取得資料實體:
HttpEntity resEntity = response.getEntity();
複製代碼
你可以把它轉成字串來使用:
result = EntityUtils.toString(resEntity);
複製代碼
以上就是Get的基本操作。
Post的使用步驟
一樣先建立HttpClient物件:
HttpClient client = new DefaultHttpClient();
複製代碼
接著建立HttpPost物件並傳入網址 :
HttpPost post = new HttpPost(_url);
複製代碼
如果有參數的話,可以這樣加入:
List<NameValuePair> params = new ArrayList<NameValuePair>();
複製代碼
取得資料實體後可以轉成字串來用:
HttpEntity resEntity = responsePOST.getEntity();
result = EntityUtils.toString(resEntity);
複製代碼
以上是Post的操作方式。在參數的部份,接下來的範例只能加入一對(key-value),若有需要多組參數的話,要改成陣列的方式。
在Androidmanifest.xml加入網路存取權限
<uses-permission android:name="android.permission.INTERNET"/>
複製代碼
在連線結束後要斷線,在 try..catch 最後增加 finally 來斷線。
finally {
client.getConnectionManager().shutdown();
}
複製代碼
範例程式碼
package com.tonycube.demo;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GetPostDemoActivity extends Activity {
private TextView txtResult = null;
private Button btnLoad = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
private void loadPage() {
String html = getHtmlByGet("http://zh.wikipedia.org/wiki/Wiki");
txtResult.setText(html);
}
private void initView() {
txtResult = (TextView) findViewById(R.id.txtResult);
btnLoad = (Button) findViewById(R.id.btnLoad);
btnLoad.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
loadPage();
}
});
}
public String getHtmlByPost(String _url, String _queryKey, String _queryValue){
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(_url);
//參數
if (_queryKey != ""){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(_queryKey, _queryValue));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
post.setEntity(ent);
}
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return result;
}
public String getHtmlByGet(String _url){
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(_url);
HttpResponse response = client.execute(get);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return result;
}
}
複製代碼
一)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;
}
複製代碼
文章來源
歡迎光臨 TShopping (http://www.tshopping.com.tw/)
Powered by Discuz! X3.2