我們知道Android中通過Get方式提交的數據是作為Url地址的一部分進行提交,而且對字節數的長度也有限制,與Get方式類似,http-post參數也是被URL編碼的,然而它的變量名和變量值不作為URL的一部分被傳送,而是放在實際的HTTP請求消息內部被傳送。
可以通過如下的代碼設置POST提交方式參數:
- HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
- urlConnection.setConnectTimeout(3000);
- urlConnection.setRequestMethod("POST"); //以post請求方式提交
- urlConnection.setDoInput(true); //讀取數據
- urlConnection.setDoOutput(true); //向服務器寫數據
- //獲取上傳信息的大小和長度
- byte[] myData = stringBuilder.toString().getBytes();
- //設置請求體的類型是文本類型,表示當前提交的是文本數據
- urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- urlConnection.setRequestProperty("Content-Length", String.valueOf(myData.length));
這裡使用一個案例來看一下如何使用post方式提交數據到服務器:
首先我們創建一個java project,只要創建一個類就行,我們創建一個HttpUtils.java類,
【代碼如下】:
- package com.wujay.utils;
-
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.Map;
-
- public class HttpUtils {
- private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 服務端地址
- private static URL url;
-
- public HttpUtils() {
- super();
- }
-
- // 靜態代碼塊實例化url
- static {
- try {
- url = new URL(PATH);
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 發送消息體到服務端
- *
- * @param params
- * @param encode
- * @return
- */
- public static String sendPostMessage(Map<String, String> params,
- String encode) {
- StringBuilder stringBuilder = new StringBuilder();
- if (params != null && !params.isEmpty()) {
- for (Map.Entry<String, String> entry : params.entrySet()) {
- try {
- stringBuilder
- .append(entry.getKey())
- .append("=")
- .append(URLEncoder.encode(entry.getValue(), encode))
- .append("&");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- stringBuilder.deleteCharAt(stringBuilder.length() - 1);
- try {
- HttpURLConnection urlConnection = (HttpURLConnection) url
- .openConnection();
- urlConnection.setConnectTimeout(3000);
- urlConnection.setRequestMethod("POST"); // 以post請求方式提交
- urlConnection.setDoInput(true); // 讀取數據
- urlConnection.setDoOutput(true); // 向服務器寫數據
- // 獲取上傳信息的大小和長度
- byte[] myData = stringBuilder.toString().getBytes();
- // 設置請求體的類型是文本類型,表示當前提交的是文本數據
- urlConnection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- urlConnection.setRequestProperty("Content-Length",
- String.valueOf(myData.length));
- // 獲得輸出流,向服務器輸出內容
- OutputStream outputStream = urlConnection.getOutputStream();
- // 寫入數據
- outputStream.write(myData, 0, myData.length);
- outputStream.close();
- // 獲得服務器響應結果和狀態碼
- int responseCode = urlConnection.getResponseCode();
- if (responseCode == 200) {
- // 取回響應的結果
- return changeInputStream(urlConnection.getInputStream(),
- encode);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
- return "";
- }
-
- /**
- * 將一個輸入流轉換成指定編碼的字符串
- *
- * @param inputStream
- * @param encode
- * @return
- */
- private static String changeInputStream(InputStream inputStream,
- String encode) {
-
- // 內存流
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- byte[] data = new byte[1024];
- int len = 0;
- String result = null;
- if (inputStream != null) {
- try {
- while ((len = inputStream.read(data)) != -1) {
- byteArrayOutputStream.write(data, 0, len);
- }
- result = new String(byteArrayOutputStream.toByteArray(), encode);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return result;
- }
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- Map<String, String> map = new HashMap<String, String>();
- map.put("username", "admin");
- map.put("password", "123456");
- String result = sendPostMessage(map, "UTF-8");
- System.out.println(">>>" + result);
- }
-
- }