我们知道通过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 params,
String encode) {
StringBuilder stringBuilder = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry 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 map = new HashMap();
map.put("username", "admin");
map.put("password", "123456");
String result = sendPostMessage(map, "UTF-8");
System.out.println(">>>" + result);
}
}
我们再创建一个服务端工程,一个web project,这里创建一个myhttp的工程,先给它创建一个servlet,用来接收参数访问。
创建的servlet配置如下:
This is the description of my J2EE component
This is the display name of my J2EE component
LoginAction
com.login.manager.LoginAction
LoginAction
/servlet/LoginAction
建立的LoginAction.java类继承HttpServlet:
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.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* 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.
*
* 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{
out.print("login failed");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
我们运行java project,控制台输出如下:
>>>login successful!