我們知道通過Get方式提交的數據是作為Url地址的一部分進行提交,而且對字節數的長度也有限制,與Get方式類似,http-post參數也是被URL編碼的,然而它的變量名和變量值不作為URL的一部分被傳送,而是放在實際的HTTP請求消息內部被傳送。
可以通過如下的代碼設置POST提交方式參數:
[html]
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類,
【代碼如下】:
[html]
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);
}
}
我們再創建一個服務端工程,一個web project,這裡創建一個myhttp的工程,先給它創建一個servlet,用來接收參數訪問。
創建的servlet配置如下:
[html]
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginAction</servlet-name>
<servlet-class>com.login.manager.LoginAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginAction</servlet-name>
<url-pattern>/servlet/LoginAction</url-pattern>
</servlet-mapping>
建立的LoginAction.java類繼承HttpServlet:
[html]
package com.login.manager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginAction extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
System.out.println("userName:"+userName);
System.out.println("passWord:"+passWord);
if(userName.equals("admin") && passWord.equals("123456")){
out.print("login successful!");
}else{ www.2cto.com
out.print("login failed");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}