post提交数据

我们知道通过Get方式提交的数据是作为Url地址的一部分进行提交,而且对字节数的长度也有限制,与Get方式类似,http-post参数也是被URL编码的,然而它的变量名和变量值不作为URL的一部分被传送,而是放在实际的HTTP请求消息内部被传送。

可以通过如下的代码设置POST提交方式参数:

  1. HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); 
  2. urlConnection.setConnectTimeout(3000); 
  3. urlConnection.setRequestMethod("POST"); //以post请求方式提交 
  4. urlConnection.setDoInput(true);     //读取数据 
  5. urlConnection.setDoOutput(true);    //向服务器写数据 
  6. //获取上传信息的大小和长度 
  7. byte[] myData = stringBuilder.toString().getBytes(); 
  8. //设置请求体的类型是文本类型,表示当前提交的是文本数据 
  9. urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
  10. urlConnection.setRequestProperty("Content-Length", String.valueOf(myData.length)); 
	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类,

【代码如下】:

  1. package com.wujay.utils; 
  2.  
  3. import java.io.ByteArrayOutputStream; 
  4. import java.io.IOException; 
  5. import java.io.InputStream; 
  6. import java.io.OutputStream; 
  7. import java.io.UnsupportedEncodingException; 
  8. import java.net.HttpURLConnection; 
  9. import java.net.MalformedURLException; 
  10. import java.net.URL; 
  11. import java.net.URLEncoder; 
  12. import java.util.HashMap; 
  13. import java.util.Map; 
  14.  
  15. public class HttpUtils { 
  16.     private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 服务端地址 
  17.     private static URL url; 
  18.  
  19.     public HttpUtils() { 
  20.         super(); 
  21.     } 
  22.  
  23.     // 静态代码块实例化url 
  24.     static { 
  25.         try { 
  26.             url = new URL(PATH); 
  27.         } catch (MalformedURLException e) { 
  28.             e.printStackTrace(); 
  29.         } 
  30.     } 
  31.  
  32.     /** 
  33.      * 发送消息体到服务端 
  34.      *  
  35.      * @param params 
  36.      * @param encode 
  37.      * @return 
  38.      */ 
  39.     public static String sendPostMessage(Map<String, String> params, 
  40.             String encode) { 
  41.         StringBuilder stringBuilder = new StringBuilder(); 
  42.         if (params != null && !params.isEmpty()) { 
  43.             for (Map.Entry<String, String> entry : params.entrySet()) { 
  44.                 try { 
  45.                     stringBuilder 
  46.                             .append(entry.getKey()) 
  47.                             .append("=") 
  48.                             .append(URLEncoder.encode(entry.getValue(), encode)) 
  49.                             .append("&"); 
  50.                 } catch (UnsupportedEncodingException e) { 
  51.                     e.printStackTrace(); 
  52.                 } 
  53.             } 
  54.             stringBuilder.deleteCharAt(stringBuilder.length() - 1); 
  55.             try { 
  56.                 HttpURLConnection urlConnection = (HttpURLConnection) url 
  57.                         .openConnection(); 
  58.                 urlConnection.setConnectTimeout(3000); 
  59.                 urlConnection.setRequestMethod("POST"); // 以post请求方式提交 
  60.                 urlConnection.setDoInput(true); // 读取数据 
  61.                 urlConnection.setDoOutput(true); // 向服务器写数据 
  62.                 // 获取上传信息的大小和长度 
  63.                 byte[] myData = stringBuilder.toString().getBytes(); 
  64.                 // 设置请求体的类型是文本类型,表示当前提交的是文本数据 
  65.                 urlConnection.setRequestProperty("Content-Type", 
  66.                         "application/x-www-form-urlencoded"); 
  67.                 urlConnection.setRequestProperty("Content-Length", 
  68.                         String.valueOf(myData.length)); 
  69.                 // 获得输出流,向服务器输出内容 
  70.                 OutputStream outputStream = urlConnection.getOutputStream(); 
  71.                 // 写入数据 
  72.                 outputStream.write(myData, 0, myData.length); 
  73.                 outputStream.close(); 
  74.                 // 获得服务器响应结果和状态码 
  75.                 int responseCode = urlConnection.getResponseCode(); 
  76.                 if (responseCode == 200) { 
  77.                     // 取回响应的结果 
  78.                     return changeInputStream(urlConnection.getInputStream(), 
  79.                             encode); 
  80.                 } 
  81.             } catch (IOException e) { 
  82.                 e.printStackTrace(); 
  83.             } 
  84.  
  85.         } 
  86.         return ""; 
  87.     } 
  88.  
  89.     /** 
  90.      * 将一个输入流转换成指定编码的字符串 
  91.      *  
  92.      * @param inputStream 
  93.      * @param encode 
  94.      * @return 
  95.      */ 
  96.     private static String changeInputStream(InputStream inputStream, 
  97.             String encode) { 
  98.  
  99.         // 内存流 
  100.         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
  101.         byte[] data = new byte[1024]; 
  102.         int len = 0
  103.         String result = null
  104.         if (inputStream != null) { 
  105.             try { 
  106.                 while ((len = inputStream.read(data)) != -1) { 
  107.                     byteArrayOutputStream.write(data, 0, len); 
  108.                 } 
  109.                 result = new String(byteArrayOutputStream.toByteArray(), encode); 
  110.             } catch (IOException e) { 
  111.                 e.printStackTrace(); 
  112.             } 
  113.         } 
  114.         return result; 
  115.     } 
  116.  
  117.     /** 
  118.      * @param args 
  119.      */ 
  120.     public static void main(String[] args) { 
  121.         Map<String, String> map = new HashMap<String, String>(); 
  122.         map.put("username", "admin"); 
  123.         map.put("password", "123456"); 
  124.         String result = sendPostMessage(map, "UTF-8"); 
  125.         System.out.println(">>>" + result); 
  126.     } 
  127.  
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配置如下:

  1. <servlet> 
  2.         <description>This is the description of my J2EE component</description> 
  3.         <display-name>This is the display name of my J2EE component</display-name> 
  4.         <servlet-name>LoginAction</servlet-name> 
  5.         <servlet-class>com.login.manager.LoginAction</servlet-class> 
  6.     </servlet> 
  7.  
  8.     <servlet-mapping> 
  9.         <servlet-name>LoginAction</servlet-name> 
  10.         <url-pattern>/servlet/LoginAction</url-pattern> 
  11.     </servlet-mapping> 
<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:

  1. package com.login.manager; 
  2.  
  3. import java.io.IOException; 
  4. import java.io.PrintWriter; 
  5.  
  6. import javax.servlet.ServletException; 
  7. import javax.servlet.http.HttpServlet; 
  8. import javax.servlet.http.HttpServletRequest; 
  9. import javax.servlet.http.HttpServletResponse; 
  10.  
  11. public class LoginAction extends HttpServlet { 
  12.  
  13.     /** 
  14.      * Constructor of the object. 
  15.      */ 
  16.     public LoginAction() { 
  17.         super(); 
  18.     } 
  19.  
  20.     /** 
  21.      * Destruction of the servlet. <br> 
  22.      */ 
  23.     public void destroy() { 
  24.         super.destroy(); // Just puts "destroy" string in log 
  25.         // Put your code here 
  26.     } 
  27.  
  28.     /** 
  29.      * The doGet method of the servlet. <br> 
  30.      * 
  31.      * This method is called when a form has its tag value method equals to get. 
  32.      *  
  33.      * @param request the request send by the client to the server 
  34.      * @param response the response send by the server to the client 
  35.      * @throws ServletException if an error occurred 
  36.      * @throws IOException if an error occurred 
  37.      */ 
  38.     public void doGet(HttpServletRequest request, HttpServletResponse response) 
  39.             throws ServletException, IOException { 
  40.             this.doPost(request, response); 
  41.     } 
  42.  
  43.     /** 
  44.      * The doPost method of the servlet. <br> 
  45.      * 
  46.      * This method is called when a form has its tag value method equals to post. 
  47.      *  
  48.      * @param request the request send by the client to the server 
  49.      * @param response the response send by the server to the client 
  50.      * @throws ServletException if an error occurred 
  51.      * @throws IOException if an error occurred 
  52.      */ 
  53.     public void doPost(HttpServletRequest request, HttpServletResponse response) 
  54.             throws ServletException, IOException { 
  55.  
  56.         response.setContentType("text/html;charset=utf-8"); 
  57.         request.setCharacterEncoding("utf-8"); 
  58.         response.setCharacterEncoding("utf-8"); 
  59.         PrintWriter out = response.getWriter(); 
  60.         String userName = request.getParameter("username"); 
  61.         String passWord = request.getParameter("password"); 
  62.         System.out.println("userName:"+userName); 
  63.         System.out.println("passWord:"+passWord); 
  64.         if(userName.equals("admin") && passWord.equals("123456")){ 
  65.             out.print("login successful!"); 
  66.         }else{ 
  67.             out.print("login failed"); 
  68.         } 
  69.         out.flush(); 
  70.         out.close(); 
  71.     } 
  72.  
  73.     /** 
  74.      * Initialization of the servlet. <br> 
  75.      * 
  76.      * @throws ServletException if an error occurs 
  77.      */ 
  78.     public void init() throws ServletException { 
  79.         // Put your code here 
  80.     } 
  81.  

转自:http://blog.csdn.net/wulianghuan/article/details/8626551

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值