服务器返回HTTP响应代码:Keycloak为400

时间:2017-11-03 05:56:31

标签: java post http-post httpurlconnection keycloak

我正在通过java应用程序访问keycloak服务器。当我在postman上运行url以及参数时,我得到了响应令牌但是当我尝试通过java做同样的事情时,它会抛出错误。以下是我的代码:

    public void login() {
    try {
    String uri = "http://localhost:7080/auth/realms/demo/protocol/openid-connect/token";
    URL url = new URL(uri);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setReadTimeout(10000);

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("grant_type", "password"));
                params.add(new BasicNameValuePair("client_id", "SuperAdminPortal"));
                params.add(new BasicNameValuePair("username", "admin"));
                params.add(new BasicNameValuePair("password", "demo"));

                OutputStream oss = con.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(oss, "UTF-8"));
                writer.write(getQuery(params));
                writer.flush();
                writer.close();
                oss.close();

                con.connect();
                con.getInputStream()
    } 
catch (Exception ex)
      {ex.printStackTrace();}
}


private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

我在第34行中得到以下错误:con.getInputStream()&#34;

11:05:08,346 ERROR [stderr] (default task-6) java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:7080/auth/realms/demo/protocol/openid-connect/token

任何信息都很明显。

2 个答案:

答案 0 :(得分:0)

您必须将内容类型更改为application/x-www-form-urlencoded。 请参阅RFC-6749 OAuth2

con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

答案 1 :(得分:0)

它仍然向我显示同样的错误。我通过编写以下代码解决了这个问题:

String uri = "http://localhost:7080/auth/realms/demo/protocol/openid-connect/token";

            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(uri);
            post.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
            List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>();
            urlParameters.add(new BasicNameValuePair("grant_type", "password"));
            urlParameters.add(new BasicNameValuePair("client_id", "SuperAdminPortal"));
            urlParameters.add(new BasicNameValuePair("username", useName));
            urlParameters.add(new BasicNameValuePair("password", password));
            post.setEntity(new UrlEncodedFormEntity(urlParameters));
            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line1 = "";
            while ((line1 = rd.readLine()) != null) {
                result.append(line1);
            }
            System.out.println(result);