我正在尝试触发一个 http post 请求,我的问题是我得到了一个 NullpointerException,我想我知道在哪里,但我不知道为什么。
代码是
HttpURLConnection connection = null;
try {
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
log.info("Http request response '{}': ",response.toString());
} catch (Exception e) {
log.error("Error while sending http post request.");
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
}
我的错误输出是:
java.lang.NullPointerException
at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:905)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1014)
在线:DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
似乎问题是要建立一个 Http URL 连接,但我的目标 URL(我要发送请求的 URL)是正确的: Target url: 'http:localhost:8080/project/externalData' (它是我的 url (Spring) RequestMethod 在我的 url 模式中。而且我的参数字符串似乎是正确的 PARAMS:'salutation=Mister&givenname=Matt&familyname=Jones'。或者使用 DataOutputStream 是否正确?
感谢任何帮助:)