我想发送 {"名称":"超级用户","状态":1} 但是当我发送i时得到这个错误
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at com.service.RoleService.updateRole(RoleService.java:145)
at com.service.RoleService.main(RoleService.java:176)
这是代码
URL url = new URL("http://localhost:31109/user/role/"+role_id);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("PUT");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setConnectTimeout(15000);
String input = "{\"name\":\""+name+"\",\"status\":"+status+"}";
System.out.println(input);
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
if(httpConnection.getResponseCode() !=200){
String error_resp;
BufferedReader error_responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getErrorStream())));
while((error_resp = error_responseBuffer.readLine()) != null){
System.out.println("Error responsecode => "+httpConnection.getResponseCode()+"error => "+error_resp);
output = new JSONObject(error_resp);
}
}else {
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String httpresponse;
StringBuilder content = new StringBuilder();
while((httpresponse = responseBuffer.readLine()) != null){
content.append(httpresponse);
}
output = new JSONObject(content.toString());
}
httpConnection.disconnect();
然而,当我发送 {&#34;名称&#34;:&#34;超级用户&#34;,&#34;状态&#34;:&#34; 1&#34;} 请求没问题,但API有一个验证,要求将其作为整数发送并拒绝它。我无法改变api。
答案 0 :(得分:0)
您正在尝试为URL调用的响应创建一个Reader,但套接字可能已经关闭。您应检查httpConnection.getXXXStream调用以确保httpConnection仍处于活动状态,并且getStream调用的返回值不为null。
- 编辑 -
您对responseCode != 200
的检查是个问题。 100s和200s中的响应代码都不是错误,并且不会使用错误流。否则,您应该检查您从httpConnection获取的输入流,例如
if(httpConnection.getResponseCode() !=200){
String error_resp;
InputStream in = httpConnection.getErrorStream();
if (in == null) return; // check if the error stream is null
BufferedReader error_responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getErrorStream())));
while((error_resp = error_responseBuffer.readLine()) != null){
System.out.println("Error responsecode => "+httpConnection.getResponseCode()+"error => "+error_resp);
output = new JSONObject(error_resp);
}
}else {
InputStream in = httpConnection.getInputStream();
if (in == null) return; // check inputstream
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(in)));
String httpresponse;
StringBuilder content = new StringBuilder();
while((httpresponse = responseBuffer.readLine()) != null){
content.append(httpresponse);
}
output = new JSONObject(content.toString());
}
httpConnection.disconnect();