Spring Boot:POST 请求返回 401 HttpUrlConnection

huangapple 未分类评论73阅读模式
英文:

Spring Boot : POST request returns 401 HttpUrlConnection

问题

public String requestToken() throws Exception {

    StringBuilder response = new StringBuilder();

    URL url = new URL("https://xyz.auth0.com/oauth/token");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod(TokenConstant.METHOD_POST);

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");

    connection.setRequestProperty("Accept", "application/json");
    connection.setDoOutput(true);

    String jsonInputString = "grant_type=client_credentials&client_id=xyz&client_secret=abc&audience=https://xyz.abc.com";

    try (OutputStream outputStream = connection.getOutputStream()) {
        byte[] input = jsonInputString.getBytes("utf-8");
        outputStream.write(input, 0, input.length);
    }

    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(
                    connection.getInputStream(), "utf-8"))) {
        String responseLine = null;
        while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
        }
    }
    return response.toString();
}
英文:

I'm using HttpURLConnection to send a POST request to get the access token. However, I get the error says
java.io.IOException: Server returned HTTP response code: 401 for URL: https://xyz.auth0.com/oauth/token

Note: I'm able to get the access token via Postman.

Can someone please help me? Thanks in advance!

public String requestToken() throws Exception{

        StringBuilder response = new StringBuilder();

        URL url = new URL("https://xyz.auth0.com/oauth/token");
        //open a connection
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();

        //set the request method
        connection.setRequestMethod(TokenConstant.METHOD_POST);

        //set the request content-type header parameter
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");

        //set response format type
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);

        //create request parameter
        String jsonInputString = "grant_type=client_credentials&client_id=xyz&client_secret=abc&audience=https://xyz.abc.com}";;
        // we need to write it
        try(OutputStream outputStream = connection.getOutputStream()){
            byte[] input = jsonInputString.getBytes("utf-8");
            outputStream.write(input, 0, input.length);
        }

        //Read the response from Input Stream
        //get the input stream to read the response content
        try(BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        connection.getInputStream(),"utf-8"))){
            String responseLine = null;
            while((responseLine = br.readLine()) != null){
                response.append(responseLine.trim());
            }
        }
        return response.toString();
    }

答案1

得分: 0

public static String requestToken() throws Exception{

    StringBuilder response = new StringBuilder();

    URL url = new URL("https://graph.facebook.com/oauth/access_token");
    // 打开连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // 设置请求方法
    connection.setRequestMethod("GET");

    // 设置请求内容类型头参数
    // 注释 - 不需要
    /*connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");*/

    // 设置响应格式类型
    connection.setRequestProperty("Accept", "application/json");
    connection.setDoOutput(true);

    // 创建请求参数
    String jsonInputString = "client_id=<your-app-id>&client_secret=<your-app-secret>&grant_type=client_credentials";
    // 需要写入
    try (OutputStream outputStream = connection.getOutputStream()) {
        byte[] input = jsonInputString.getBytes("utf-8");
        outputStream.write(input, 0, input.length);
    }

    // 读取输入流中的响应
    // 获取输入流以读取响应内容
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(
                    connection.getInputStream(), "utf-8"))) {
        String responseLine = null;
        while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
        }
    }
    return response.toString();
}
英文:

Sample curl facebook oauth access token generation (GET request) - To generate an app access token:

curl -X GET &quot;https://graph.facebook.com/oauth/access_token
?client_id={your-app-id}
  &amp;client_secret={your-app-secret}
  &amp;grant_type=client_credentials&quot;

Commented few headers - Not required. Changed request to GET.
NOTE: if it works fine with curl, then your code might work fine, with few modifications.

public static String requestToken() throws Exception{

    StringBuilder response = new StringBuilder();

    URL url = new URL(&quot;https://graph.facebook.com/oauth/access_token&quot;);
    //open a connection
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();

    //set the request method
    connection.setRequestMethod(&quot;GET&quot;);

    //set the request content-type header parameter
    // Commented - not required
    /*connection.setRequestProperty(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);
    connection.setRequestProperty(&quot;charset&quot;, &quot;utf-8&quot;);*/


    //set response format type
    connection.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;);
    connection.setDoOutput(true);

    //create request parameter
    String jsonInputString = &quot;client_id=&lt;your-app-id&gt;&amp;client_secret=&lt;your-app-secret&gt;&amp;grant_type=client_credentials&quot;;;
    // we need to write it
    try(OutputStream outputStream = connection.getOutputStream()){
        byte[] input = jsonInputString.getBytes(&quot;utf-8&quot;);
        outputStream.write(input, 0, input.length);
    }

    //Read the response from Input Stream
    //get the input stream to read the response content
    try(BufferedReader br = new BufferedReader(
            new InputStreamReader(
                    connection.getInputStream(),&quot;utf-8&quot;))){
        String responseLine = null;
        while((responseLine = br.readLine()) != null){
            response.append(responseLine.trim());
        }
    }
    return response.toString();
}

huangapple
  • 本文由 发表于 2020年8月15日 01:09:30
  • 转载请务必保留本文链接:https://java.coder-hub.com/63417194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定