第一个是TestIOSServlet的内容,通过网络编程的方式
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//该servlet用来模拟手机平台发送的json字符串和md5字符串。
PrintWriter out = null;
response.setContentType(CONTENT_TYPE);
out = response.getWriter();
String appMsg=request.getParameter("appMsg");//json字符串
HashMap requestXmlMap=new HashMap();
if(appMsg!=null){
appMsg=appMsg.replaceAll(""", "\"");;//转成双引号
}
log.info("传过来的json字符串:"+appMsg);
try {
requestXmlMap= (HashMap) JsonUtil.getMapFromJson(appMsg);
String MD5=AutoMd5(requestXmlMap);
// request.getRequestDispatcher("/servlet/AppIOSServlet?MD5="+MD5+"").forward(request, response);
String strUrl="http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/servlet/AppIOSServlet?MD5="+MD5+"";
URL url = new URL(strUrl);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("content-type", "text/html");
OutputStream outs=con.getOutputStream();
outs.write(appMsg.getBytes("UTF-8"));
InputStream in = con.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String outtext="";
try {
String line="";
int i=0;
while ( (line=read.readLine())!= null ) {
outtext += line + "\n";
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
log.info("json字符串"+outtext);
read.close();
in.close();
outs.close();
out.print(outtext);
}catch (Exception e) {
e.printStackTrace();
}finally{
out.flush();
out.close();
}
}
另外一个AppIOSServlet接受传递过来的参数
//服务器端用request.getInputStream() 从流里面读JSON字符串
BufferedReader br = new BufferedReader(new InputStreamReader(
(ServletInputStream) request.getInputStream()));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
String appMsg=sb.toString();
传递过来的参数appMsg就从流里面读取到,最后返回的值仍会返回到TestIOSServlet中去