Android使用HttpURLConnection发送Post请求到服务端

android端部分代码
private void postDataByHttp()
	{
		String urlString = "http://192.168.191.1:8080/TestHttp/MyJsp.jsp";//URL根据自己部署的服务修改
		String resultData = "";
		String outData = "userName=ceshi&userPassword=123456";		//数据可以随意填写
		
		URL url= null;
		try
		{
			url= new URL(urlString);
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] entity = outData.getBytes();
		try
		{
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);	//允许接受数据流
			connection.setDoOutput(true);//允许数据流发送出去
			connection.setConnectTimeout(5000); //设置超时
			connection.setReadTimeout(5000);//设置读取超时
			connection.setRequestMethod("POST");//POST方式发送数据
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length", String.valueOf(entity.length));
			
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(entity);
			
			if(connection.getResponseCode() == 200)	//返回码是200为正常
			{
				InputStream inputStream  = connection.getInputStream();	//获取返回的数据流
				InputStreamReader streamReader = new InputStreamReader(inputStream);
				BufferedReader bufferedReader = new BufferedReader(streamReader);
				
				String inputLine = null;
				
				while((inputLine = bufferedReader.readLine()) != null)
				{
					resultData  += inputLine + "\r\n";
				}
				
				Sysout.out.println(resultData );
				bufferedReader.close();
				streamReader.close();
				inputStream.close();
				connection.disconnect();
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
服务器端接受数据MyJsp.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.net.URLEncoder"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<%
	String strUserName = request.getParameter("userName");
	String strPassword = request.getParameter("userPassword");

	//因为Tomcat的编码格式为ISO8859-1

	String title = new String(strUserName.getBytes("ISO8859-1"),"UTF-8");//对发送的文字格式进行编码,防止汉字乱码
	System.out.println(title);
	System.out.println(strPassword);
	response.getWriter().print(title + "--" + strPassword);
%>

你可能感兴趣的:(android,post)