无法使用httpconnectionurl和outstreamwriter进行post调用



下面是我正在测试的代码。当我运行这个,我看到后体是空的。当我在服务器端跟踪时,我可以看到所有的头,但主体是空的。你能指出我这里的错误吗?

String jsonstring = "{"id":"1233", "userName" : "jump2"}";
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonstring);
System.out.println(jsonObject.toJSONString());
Long currentTime = System.currentTimeMillis();
URL restUrl = new URL("http://myservers.com/v1/register");
HttpURLConnection urlConnection = (HttpURLConnection) restUrl.openConnection();
urlConnection.addRequestProperty("X-CORRELATION-ID", currentTime.toString());
urlConnection.addRequestProperty("X-AUTH-APIKEY", "dDEdfaeFFDdddDF");
urlConnection.addRequestProperty("Accept","application/json");
urlConnection.addRequestProperty("Content-Type","application/json");
urlConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
jsonObject.writeJSONString(outputStreamWriter);
System.out.println(urlConnection.getResponseCode());
System.out.println(urlConnection.getRequestMethod());
System.out.println(urlConnection.getContentEncoding());
outputStreamWriter.flush();
outputStreamWriter.close();
urlConnection.disconnect();```

您必须将请求方法设置为POST

urlConnection.setRequestMethod("POST");

HttpUrlConnection示例

最新更新