java发送post请求以json数组形式

public static void dspDaoRu(DspNews dspNews) throws Exception {
String result = "";
// 添加url参数
Map<String, Object> map = new HashMap<String, Object>();
// JSONObject obj = new JSONObject();
map.put("name", dspNews.getName());
map.put("sex", "0");
map.put("phone", dspNews.getMobile());
map.put("customerSource", QuDao.getNameByValue(dspNews.getFromWeb()));// 渠道
map.put("belongProvince", dspNews.getProvince());// 首先做判断
map.put("belongCity", dspNews.getCity());// 城市
map.put("adCode", dspNews.getDspNumber() + "-" + dspNews.getAdGroup() + "-" + dspNews.getPageNumber());// 页面广告组创意
map.put("customerSituation", "无");// 客户情况

JSONArray json = JSONArray.fromObject(map);

                //打印格式样式

System.err.println( json.toString());
sendPostUrlTwo(URL, json.toString());

}

public static JSONObject sendPostUrlTwo(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
JSONObject jsonObject = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);

conn.setDoInput(true);

conn.setRequestProperty("token", token);//设置请求头所需token验证
conn.setRequestProperty("Content-Type", "application/json");
// 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
System.err.println(out);
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 获取请求返回数据(设置返回数据编码为UTF-8)
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.err.println(result);//打印返回结果   
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}


return jsonObject;

}

//如果提交的时候报500错误,需要检查提交的json格式,和提交字段,是否与接口一致!

猜你喜欢

转载自blog.csdn.net/qq_39719302/article/details/80723014