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";<span style="white-space:pre">		</span>//数据可以随意填写
		
		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)<span style="white-space:pre">	</span>//返回码是200为正常
			{
				InputStream inputStream  = connection.getInputStream();<span style="white-space:pre">	</span>//获取返回的数据流
				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+"/";
%>


<%
<span style="white-space:pre">	</span>String strUserName = request.getParameter("userName");
<span style="white-space:pre">	</span>String strPassword = request.getParameter("userPassword");

<span style="white-space:pre">	</span>//因为Tomcat的编码格式为ISO8859-1

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值