代码演示
public static void send(PuKe puke){
String url = "http://43.143.5.149:30020/api/v4/send";
OutputStream outputStream = null;
BufferedInputStream bis = null;
ByteArrayOutputStream bos = null;
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
conn.setRequestProperty("Content-Type","application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.connect();
String jsonString = JSON.toJSONString(puke);
if (jsonString != null){
outputStream = conn.getOutputStream();
outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
}
bis = new BufferedInputStream(conn.getInputStream());
bos = new ByteArrayOutputStream();
int len = -1;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1){
bos.write(bytes,0,len);
}
String s = bos.toString();
System.out.println(s);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (outputStream != null){
outputStream.close();
}
if (bis != null){
bis.close();
}
if (bos != null){
bos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}