我想在java中调用一个安静的Web服务,我也想发送内容类型和(用户名+密码作为头文件中的基本身份验证。我在我的代码中设置所有内容如下:
public class restClient {
public static void main(String[] args) throws Exception{
String payload="{\"username\":myuser,\"password\":\"mypass\",\"nationalCode\":\"1234567890\"}";
String requestUrl="http://192.168.1.1/myService/GetCoverage";
sendPostRequest(requestUrl, payload);
}
public static String sendPostRequest(String requestUrl, String payload) throws Exception {
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
System.out.println("------------> " + connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
}
虽然我已经添加了所有参数,但我无法得到响应,我在我的intelij IDEA控制台中看到了这些错误:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.0.233.254/vezaratkar/GetCoverage
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626)
at com.mkyong.restClient.sendPostRequest(restClient.java:50)
at com.mkyong.restClient.main(restClient.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
我该如何解决这个问题?