String serverURL = "http://*************";
HttpURLConnection connection = null;
BufferedReader reader = null;
InputStream is = null;
OutputStreamWriter writer = null;
try{
StringBuffer sbf = new StringBuffer();
String strRead = null;
URL url = new URL(serverURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");//请求post方式
connection.setDoInput(true);
connection.setDoOutput(true);
//header内的的参数在这里set
connection.setRequestProperty("******","******");
connection.setRequestProperty("******","******");
//connection.setRequestProperty("key", "value");
connection.setRequestProperty("Content-Type", "application/json;charset=\"UTF-8\"");
connection.connect();
writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
//body参数放这里
JSONObject params = new JSONObject();
params.put(" ",false);
params.put(" "," ");
writer.write(params.toString());
writer.flush();
is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
is.close();
writer.close();
connection.disconnect();
String results = sbf.toString();
System.out.println("str_base>>>:"+results);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if(connection != null){
connection.disconnect();
}
if(reader != null){
reader.close();
}
if(is != null){
is.close();
}
if(writer != null){
writer.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
javapost请求带body测试代码
于 2023-07-12 17:53:20 首次发布