Android中使用Post请求
一、需要用到的場景
在jQuery中使用$.post()就可以方便的發(fā)起一個post請求,在android程序中有時也要從服務(wù)器獲取一些數(shù)據(jù),就也必須得使用post請求了。
二、需要用到的主要類
在android中使用post請求主要要用到的類是HttpPost、HttpResponse、EntityUtils
三、主要思路
1、創(chuàng)建HttpPost實例,設(shè)置需要請求服務(wù)器的url。
2、為創(chuàng)建的HttpPost實例設(shè)置參數(shù),參數(shù)設(shè)置時使用鍵值對的方式用到NameValuePair類。
3、發(fā)起post請求獲取返回實例HttpResponse
4、使用EntityUtils對返回值的實體進行處理(可以取得返回的字符串,也可以取得返回的byte數(shù)組)
代碼也比較簡單,注釋也加上了,就直接貼出來了
[java]
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 = "
// 第一步,創(chuàng)建HttpPost對象
HttpPost httpPost = new HttpPost(url);
// 設(shè)置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 {
// 設(shè)置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方法活得返回結(jié)果
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請求
[java]
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());
============================================================================================================================
通過get和post方式向服務(wù)器發(fā)送請求
首先說一下get和post的區(qū)別
get請求方式是將提交的參數(shù)拼接在url地址后面,例如http://www.baidu.com/index.jsp?num=23&jjj=888;
但是這種形式對于那種比較隱私的參數(shù)是不適合的,而且參數(shù)的大小也是有限制的,一般是1K左右吧,對于上傳文件
就不是很適合。
post請求方式是將參數(shù)放在消息體內(nèi)將其發(fā)送到服務(wù)器,所以對大小沒有限制,對于隱私的內(nèi)容也比較合適。
如下Post請求
POST /LoginCheck HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://192.168.2.1/login.asp
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 192.168.2.1
Content-Length: 39
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: language=en
Username=admin&checkEn=0&Password=admin //參數(shù)位置
在android中用get方式向服務(wù)器提交請求:
在android模擬器中訪問本機中的tomcat服務(wù)器時,注意:不能寫localhost,因為模擬器是一個單獨的手機系統(tǒng),所以要寫真是的IP地址。
否則無法訪問到服務(wù)器。
//要訪問的服務(wù)器地址,下面的代碼是要向服務(wù)器提交用戶名和密碼,提交時中文先要經(jīng)過URLEncoder編碼,因為模擬器默認的編碼格式是utf-8
//而tomcat內(nèi)部默認的編碼格式是ISO8859-1,所以先將參數(shù)進行編碼,再向服務(wù)器提交。
private String address = "http://192.168.2.101:80/server/loginServlet";
public boolean get(String username, String password) throws Exception {
username = URLEncoder.encode(username);// 中文數(shù)據(jù)需要經(jīng)過URL編碼
password = URLEncoder.encode(password);
String params = "username=" + username + "&password=" + password;
//將參數(shù)拼接在URl地址后面
URL url = new URL(address + "?" + params);
//通過url地址打開連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//設(shè)置超時時間
conn.setConnectTimeout(3000);
//設(shè)置請求方式
conn.setRequestMethod("GET");
//如果返回的狀態(tài)碼是200,則一切Ok,連接成功。
return conn.getResponseCode() == 200;
}
在android中通過post方式提交數(shù)據(jù)。
public boolean post(String username, String password) throws Exception {
username = URLEncoder.encode(username);// 中文數(shù)據(jù)需要經(jīng)過URL編碼
password = URLEncoder.encode(password);
String params = "username=" + username + "&password=" + password;
byte[] data = params.getBytes();
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
//這是請求方式為POST
conn.setRequestMethod("POST");
//設(shè)置post請求必要的請求頭
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 請求頭, 必須設(shè)置
conn.setRequestProperty("Content-Length", data.length + "");// 注意是字節(jié)長度, 不是字符長度
conn.setDoOutput(true);// 準(zhǔn)備寫出
conn.getOutputStream().write(data);// 寫出數(shù)據(jù)
return conn.getResponseCode() == 200;
}