java后端请求调用三方接口
java
/**
* @param serverURL http接口地址(例:http://www.iwsu.top:8016/dataSyn/bay/statsCar)
* @param parm 参数(可以是json,也可以是json数组)
*/
public void doRestfulPostBody(String serverURL, JSONArray parm) {
System.out.println("请求的地址 =" + serverURL);
String result= "";
System.out.println("提交的数据 ="+parm);
try {
StringBuffer sbf = new StringBuffer();
String strRead = null;
URL url = new URL(serverURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");//请求post方式
connection.setDoInput(true);
connection.setDoOutput(true);
//header内的的参数在这里set
connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setRequestProperty("Cookie", Cookie);
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
//body参数在这里put到JSONObject中
writer.write(parm.toString());
writer.flush();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
connection.disconnect();
result = sbf.toString();
System.out.println("返回的数据 ="+result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}