注意:在此期间由于中文乱码问题所以下文使用的是writeChars,简要说明wrietChars和writeBytes的区别:
相同点:writeBytes(String) 和writeChars(String) 都是接收 String 参数
不同点:writeBytes(String) 依次写入字符串中的每一个字符,并且只写入字符的低8位,高字节被抛弃。
writeChars(String) 依次写入字符串中的每一个字符,字符的2个字节全部写入。
使用POST请求传递JSON格式数据,示例如下:
static JSONObject jsonResult = new JSONObject();
static JSONObject jsonBody = new JSONObject();
static JSONObject jsonData = new JSONObject();
public static void HeaderJson(String operatetype){
JSONObject jsonHeader = new JSONObject();
jsonHeader.put("orisys", "0");
jsonHeader.put("operatetype", operatetype);
jsonBody.put("header", jsonHeader);
}
public static String getResult(int size){
if(size==0){
jsonResult.put("status", "0");
jsonResult.put("message", "推送成功");
Object object = new Object();
jsonResult.put("data", JSONObject.fromObject(object));
System.out.println(jsonResult.toString());
return jsonData.toString();
}else{
jsonResult.put("status", "1");
jsonResult.put("message", "推送失败");
Object object = new Object();
jsonResult.put("data", JSONObject.fromObject(object));
System.out.println(jsonResult.toString());
return jsonResult.toString();
}
}
/**
* 销售订单上报
* @return
* @throws SQLException
*/
public static String salesOrder() throws SQLException {
String result = "";
try {
URL url = new URL(SendUrl.SEND_URL_SalesOrder);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestProperty("Charset", "UTF-8");
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(20000);
connection.setReadTimeout(300000);
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
SelectPostDaoImpl send = new SelectPostDaoImpl();
SalesOrder salesOrder = send.getOneSalesOrder();
HeaderJson("add");
jsonData.put("data", JSONObject.fromObject(salesOrder));
jsonBody.put("body", jsonData.toString());
// out.writeBytes(jsonBody.toString());
out.writeChars(jsonBody.toString());
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println(sb);
reader.close();
connection.disconnect();
result = getResult(0);
// deleteService.delSalesOrder();//删除临时表单基本误差测试数据
pressure_pro("salesOrderMidd");//调用存储过程,给临时表存放数据
} catch (MalformedURLException e) {
result = getResult(1);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
result = getResult(1);
e.printStackTrace();
} catch (IOException e) {
result = getResult(1);
e.printStackTrace();
}
return result;
}