1、客服端的HttpClient发送POST请求:
`
//发送JSON数据
public void httpSend(String url){
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(Constant.LOGINURI);
List<NameValuePair> nameValuePair = new ArrayList<>();
JSONObject jsonData = new JSONObject();//发送数据
JSONObject jsonObject = new JSONObject();//存放发送数据的JSON数据
jsonData.put("loginResult", loginResult);
jsonData.put("loginMode",loginMode);
jsonData.put("username",userName);
jsonData.put("password",password);
jsonObject.put("userMsg", jsonData);
nameValuePair.add(new BasicNameValuePair("jsStr", jsonObject.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"utf-8"));
//httpClient 响应,接收数据
HttpResponse httpResponse = httpClient.execute(httpPost);
// 如果响应成功
if( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
StringBuilder builder = new StringBuilder();
br = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
for(String s=br.readLine();s!=null;s=br.readLine()){
builder.append(s);
}
//转换JSON数据
JSONObject jsonRespnse = new JSONObject(builder.toString()).getJSONObject("userMsg");
httpResult = jsonRespnse.getString("loginResult");
}
br.close();
} catch (Exception e) {
}
}
2、服务端接受手机并发送响应数据:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接收数据
request.setCharacterEncoding("UTF-8");
jsStr = request.getParameter("jsStr");
JSONObject jsO = new JSONObject(jsStr).getJSONObject("userMsg");//获取用户的JSON数据
loginMode = jsO.getString("loginMode");
username = jsO.getString("username");
password = jsO.getString("password");
//响应数据
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
String json = "{\"userMsg\":{\"username\" : "+username+" , \"loginResult\":"+loginResult+"}}" ;
ServletOutputStream out = response.getOutputStream();
out.write(json.getBytes());
out.close();
}
`