有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中,将json设置为有效负载,并发送用户名、密码作为基本身份验证

我想用java调用一个restful 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)

我该如何解决这个问题


共 (0) 个答案