可使用android自帶的httpclient框架實(shí)現(xiàn)向服務(wù)器發(fā)起get或post請求,以下為完整的示例代碼:
五峰網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,五峰網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為五峰成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請找那個(gè)售后服務(wù)好的五峰做網(wǎng)站的公司定做!
1. GET 方式傳遞參數(shù)
//先將參數(shù)放入List,再對參數(shù)進(jìn)行URL編碼
ListBasicNameValuePair params = new LinkedListBasicNameValuePair();
params.add(new BasicNameValuePair("param1", "數(shù)據(jù)")); //增加參數(shù)1
params.add(new BasicNameValuePair("param2", "value2"));//增加參數(shù)2
String param = URLEncodedUtils.format(params, "UTF-8");//對參數(shù)編碼
String baseUrl = "服務(wù)器接口完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//將URL與參數(shù)拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發(fā)起GET請求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應(yīng)碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取服務(wù)器響應(yīng)內(nèi)容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2. POST方式 方式傳遞參數(shù)
//和GET方式一樣,先將參數(shù)放入List
params = new LinkedListBasicNameValuePair();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加參數(shù)1
params.add(new BasicNameValuePair("param2", "第二個(gè)參數(shù)"));//增加參數(shù)2
try {
HttpPost postMethod = new HttpPost(baseUrl);//創(chuàng)建一個(gè)post請求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數(shù)填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執(zhí)行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應(yīng)碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應(yīng)內(nèi)容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
?安卓項(xiàng)目開發(fā)第一階段完工,接下來是后臺交互。當(dāng)然,與后臺交互第一步一般都是與注冊登錄接口打交道。
? ? 不說廢話了,進(jìn)入正題···以下講的post請求,是跟https相關(guān)
? ? 1.將訪問路徑轉(zhuǎn)成URL :
? ? ? ? URLurl =newURL(path);
? ? 2.通過URL獲取連接:
? ? ? ? ?HttpURLConnection conn = (HttpURLConnection) url.openConnection();
? ? 3.設(shè)置請求方式:
? ? ? ? conn.setRequestMethod("POST");
? ? 4.設(shè)置請求超時(shí)時(shí)間:
? ? ? ? conn.setConnectTimeout(5000);
? 5.設(shè)置請求頭信息:
? ? ? ? conn.setRequestProperty("Content-type","application/json");
?6.獲取輸出流,將數(shù)據(jù)寫給服務(wù)器:
? ? ? ? 6.1 OutputStreamos = conn.getOutputStream();// 獲取輸出流
? ? ? ? 6.2 os.write(data.getBytes());// 將數(shù)據(jù)寫給服務(wù)器
? ? 7.設(shè)置響應(yīng)碼:
? ? ? ? ?int code = conn.getResponseCode();
? ? ? 7.1 請求碼200,表明請求成功,獲取返回內(nèi)容的輸入流:
? ? ? ? ? InputStream is = conn.getInputStream();
? ? ? ? ? Log.v("json","MESSAGE == "+streamToString(is));
? ? ? ? 7.2 將輸入流轉(zhuǎn)換成字符串信息:
? ? ? ?7.3 若返回值400,則是返回網(wǎng)絡(luò)異常,做出響應(yīng)的處理。
1、android.os.NetworkOnMainThreadException
? ? ?原因:
? ? ?android.os.NetworkOnMainThreadException是說不要在主線程中訪問網(wǎng)絡(luò),這個(gè)是android3.0版本開始就強(qiáng)制程序不能在主線程中訪問網(wǎng)絡(luò),要把訪問網(wǎng)絡(luò)放在獨(dú)立的線程中。
? 解決方法:(方法一親測有效,另外兩種方法未測試,想了解的請 移步至此 ···尊重原文作者勞動成果)
? ? 1 ?想要忽略這些強(qiáng)制策略問題的話,可以在onCreate()方法里面加上
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
? ? ? ? 并在方法上加上@SuppressLint("NewApi"),重試,OK。
? ? ? ?此時(shí),又拋出另一個(gè)問題······(程序猿就是不斷的解決各種問題,淚奔~~)
? 2、javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path
? 解決方法:忽略證書問題()
? ? ? 以上是百度到的方法,畢竟我只是一個(gè)剛接觸android開發(fā)才兩個(gè)月的小菜鳥,原文比較亂,整理一番供查閱。 原文出處 (尊重原文作者勞動成果)
? ? ? 我是不斷成長的mouse ···
一、需要用到的場景在jQuery中使用$.post()就可以方便的發(fā)起一個(gè)post請求,在android程序中有時(shí)也要從服務(wù)器獲取一些數(shù)據(jù),就也必須得使用post請求了。二、需要用到的主要類在android中使用post請求主要要用到的類是HttpPost、HttpResponse、EntityUtils三、主要思路1、創(chuàng)建HttpPost實(shí)例,設(shè)置需要請求服務(wù)器的url。2、為創(chuàng)建的HttpPost實(shí)例設(shè)置參數(shù),參數(shù)設(shè)置時(shí)使用鍵值對的方式用到NameValuePair類。3、發(fā)起post請求獲取返回實(shí)例HttpResponse4、使用EntityUtils對返回值的實(shí)體進(jìn)行處理(可以取得返回的字符串,也可以取得返回的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 = "192.168.2.112:8080/JustsyApp/Applet"; // 第一步,創(chuàng)建HttpPost對象 HttpPost httpPost = new HttpPost(url); // 設(shè)置HTTP POST請求參數(shù)必須用NameValuePair對象 ListNameValuePair params = new ArrayListNameValuePair(); 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 進(jìn)行post請求[java] String path = "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地址后面,例如/index.jsp?num=23jjj=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: 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=enUsername=admincheckEn=0Password=admin //參數(shù)位置在android中用get方式向服務(wù)器提交請求:在android模擬器中訪問本機(jī)中的tomcat服務(wù)器時(shí),注意:不能寫localhost,因?yàn)槟M器是一個(gè)單獨(dú)的手機(jī)系統(tǒng),所以要寫真是的IP地址。 否則無法訪問到服務(wù)器。//要訪問的服務(wù)器地址,下面的代碼是要向服務(wù)器提交用戶名和密碼,提交時(shí)中文先要經(jīng)過URLEncoder編碼,因?yàn)槟M器默認(rèn)的編碼格式是utf-8 //而tomcat內(nèi)部默認(rèn)的編碼格式是ISO8859-1,所以先將參數(shù)進(jìn)行編碼,再向服務(wù)器提交。 private String address = "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è)置超時(shí)時(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; }
public static String HttpPostMethod(String get_url,
ListNameValuePair params) {
String result = "";
HttpParams basicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(basicHttpParams, 15 * 1000);
HttpConnectionParams.setSoTimeout(basicHttpParams, 15 * 1000);
HttpClient htc = new DefaultHttpClient(basicHttpParams);
HttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(get_url);
// response = htc.execute(request);
// 設(shè)置httpPost請求參數(shù)
// 創(chuàng)建參數(shù)隊(duì)列
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");//json
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// httpResponse = new DefaultHttpClient().execute(httpPost);
httpResponse = htc.execute(httpPost);
// System.out.println(httpResponse.getStatusLine().getStatusCode());
Log.d("zh1", get_url+" " + httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 第三步,使用getEntity方法活得返回結(jié)果
result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
if(result==null||result.equals("")){
return null;
}
}else{
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result = null;
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}