您的位置:首页 > Web前端 > JavaScript

servlet post 发送,接收json

2016-01-06 00:00 701 查看
摘要: HttpURLConnection 基于servlet post 发送,接收json

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//把请求参数转换成json的形式
JSONObject params = new JSONObject();
params.put("CarID", "集G5B777");
params.put("InsuredID", "360426197712060044");

String connectUrl="url";//呼叫中心url

String strTimeOut = "3000";//3s
URL url = null;
BufferedReader reader = null;
InputStream inputStream = null;
OutputStream outputStream = null;
OutputStreamWriter writer = null;
/**
* HttpURLConnection的参数设置问题
*/
HttpURLConnection connection = null;
url = new URL(connectUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(true);
if(strTimeOut!=null){
connection.setConnectTimeout(Integer.parseInt(strTimeOut));
connection.setReadTimeout(Integer.parseInt(strTimeOut));
}
connection.connect();//连接
outputStream = connection.getOutputStream();
writer = new OutputStreamWriter(outputStream);
writer.write(params.toString());
writer.flush();
writer.close();//必须调用close方法,请求完毕
/**
* 读取返回的报文
*/
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
String strMessage = "";
String strResponse = "";
while ((strMessage = reader.readLine()) != null)
{
strResponse += strMessage;
}
reader.close();
System.out.println(strResponse);

//接收
public void doPost(HttpServletRequest r
7fe0
equest, HttpServletResponse response)
throws ServletException, IOException {
// 1. 接收数据
StringBuilder strbu = null;
String carID = null;
String insuredID=null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
strbu = new StringBuilder();
String str = "";
while ((str = reader.readLine()) != null) {
strbu.append(str);
}
//解析json
JSONObject jsonObject = JSONObject.fromObject(strbu.toString());
// 获取key 为CaseID 对应的值
carID = jsonObject.getString("CarID");
insuredID=jsonObject.getString("InsuredID");
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: