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);
%>