Android中使用Post請求的方法
本文實例講述了Android中使用Post請求的方法。分享給大家供大家參考。具體如下:
一、需要用到的場景
在jQuery中使用$.post()就可以方便的發(fā)起一個post請求,在android程序中有時也要從服務器獲取一些數(shù)據(jù),就也必須得使用post請求了。
二、需要用到的主要類
在android中使用post請求主要要用到的類是HttpPost、HttpResponse、EntityUtils
三、主要思路
1、創(chuàng)建HttpPost實例,設置需要請求服務器的url。
2、為創(chuàng)建的HttpPost實例設置參數(shù),參數(shù)設置時使用鍵值對的方式用到NameValuePair類。
3、發(fā)起post請求獲取返回實例HttpResponse
4、使用EntityUtils對返回值的實體進行處理(可以取得返回的字符串,也可以取得返回的byte數(shù)組)
代碼也比較簡單,注釋也加上了,就直接貼出來了
package com.justsy.url;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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;
public class HttpURLActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("start url...");
String url = "http://192.168.2.112:8080/JustsyApp/Applet";
// 第一步,創(chuàng)建HttpPost對象
HttpPost httpPost = new HttpPost(url);
// 設置HTTP POST請求參數(shù)必須用NameValuePair對象
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("action", "downloadAndroidApp"));
params.add(new BasicNameValuePair("packageId", "89dcb664-50a7-4bf2-aeed-49c08af6a58a"));
params.add(new BasicNameValuePair("uuid", "test_ok1"));
HttpResponse httpResponse = null;
try {
// 設置httpPost請求參數(shù)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpPost);
//System.out.println(httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 第三步,使用getEntity方法活得返回結果
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println("result:" + result);
T.displayToast(HttpURLActivity.this, "result:" + result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end url...");
setContentView(R.layout.main);
}
}
ADD:使用HttpURLConnection 進行post請求:
String path = "http://192.168.2.115:8080/android-web-server/httpConnectServlet.do?PackageID=89dcb664-50a7-4bf2-aeed-49c08af6a58a";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
System.out.println(conn.getResponseCode());
希望本文所述對大家的Android程序設計有所幫助。
相關文章
android 自定義view實現(xiàn)彩虹進度條功能
實現(xiàn)一個彩虹色進度條功能,不說明具體用途大家應該能猜到,想找別人造的輪子,但是沒有合適的,所以決定自己實現(xiàn)一個,下面小編通過實例代碼給大家分享android 自定義view實現(xiàn)彩虹進度條功能,感興趣的朋友一起看看吧2024-06-06

