更新时间:2023-01-03 20:29:22
只有在体内而不是之前编写参数后才能调用 httpCon.connect();
。您的代码应如下所示:
You should call httpCon.connect();
only after you write your parameters in the body and not before. Your code should look like this:
URL url = new URL("http://localhost:4567/");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close(); //don't forget to close the OutputStream
httpCon.connect();
//read the inputstream and print it
String result;
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
buf.write((byte) result2);
result2 = bis.read();
}
result = buf.toString();
System.out.println(result);