http的post方式连接服务器,发送数据到服务端,并获取服务端的数据

大概的流程是:客户端填写了用户名和密码,在服务端进行判断,验证密码如果正确,则返回登录成功,如果密码错误,则返回登录失败

客户端是java程序,具体代码如下:

package lgx.java.test;

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 HttpPostDemo {

	private static String PATH = "http://192.168.1.48:8080/myapp2/LoginAction";
	private static URL url;

	static {
		try {
			url = new URL(PATH);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("username", "admin");
		param.put("password", "123");
		String result = sendPostMessage(param, "utf-8");
		System.out.println("结果是" + result);
	}

	private static String sendPostMessage(Map<String, String> param,
			String encode) {
		StringBuffer buffer = new StringBuffer();
		if (param != null && !param.isEmpty()) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				try {
					buffer.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), encode))
							.append("&");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

			try {
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setRequestMethod("POST");
				connection.setDoInput(true);
				connection.setDoOutput(true);
				byte[] data = buffer.toString().getBytes();

				// 设置请求提的类型是文本类型,里面的字符串是默认的
				connection.setRequestProperty("Content-Tyte",
						"application/x-www-form-urlencoded");
				connection.setRequestProperty("Content-Length",
						String.valueOf(data.length));
				//输出流,将数据发送给服务端
				OutputStream outputStream = connection.getOutputStream();
				outputStream.write(data);
				int requestCode = connection.getResponseCode();
				if (requestCode == 200) {
					//输入流,获取服务端的数据
					return StreamToString(connection.getInputStream(), encode);
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * 将一个输入流转换成指定编码的字符串
	 * 
	 * @param inputStream  输入流
	 * @param encode  编码格式
	 * @return  字符串
	 */
	private static String StreamToString(InputStream inputStream, String encode) {
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		String result = "";
		int len = 0;
		try {
			while ((len = inputStream.read(data)) != -1) {
				arrayOutputStream.write(data, 0, len);
			}
			result = new String(arrayOutputStream.toByteArray(), encode);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}

服务端是tomcat服务端,在工程中,自己建立了servlet,servlet里的代码如下:

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;

/**
 * Servlet implementation class LoginAction
 */
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginAction() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected 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("123")){
			out.print("longin is success");
		}else{
			out.print("login is failed");
		}
	}

}

通过这两个代码,先开启服务端,再运行客户端,如果用户名和密码都正确的话,

客户端的控制台是:



结果是longin is success



服务端的控制台是:


admin---->username
123----->password


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。