public static String getJsonData(String urls, JSONObject jsonParam) {
StringBuffer sb = new StringBuffer();
HttpURLConnection conn = null;
OutputStream out = null;
try {
// 创建url 资源
URL url = new URL(urls);
// 创建http 连接
conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置不使用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
byte[] data = (jsonParam.toJSONString()).getBytes("UTF-8");
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 开始连接请求
conn.connect();
//创建写入流,写入请求的字符串
out = new DataOutputStream(conn.getOutputStream());
out.write(data);
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
// 请求返回的数据
InputStream is = conn.getInputStream();
String readLine = new String();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine);
}
responseReader.close();
return sb.toString();
}else {
System.out.println("请求失败!!!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {}
}
if(conn != null) {
conn.disconnect();
}
}
return null;
}