Problems generating OAuth access token with HttpURLConnection



  • I'm trying to make a request for a webservice that uses OAuth to generate an access token. However, although the request returns the Http 200 code, json appears only as {"errors":{"internal":["500"]}}, below the code:

    OBS: I did the same procedure by the terminal using curl and the data were normally generated.

    URL url = new URL( "https://api.myapi.com.br/api/oauth/token" );
    

    HttpURLConnection huc = ( HttpURLConnection ) url.openConnection();

    huc.setRequestMethod( "POST" );

    huc.setRequestProperty( "grant_type", "client_credentials" );
    huc.setRequestProperty( "client_id", CLIENT_ID );
    huc.setRequestProperty( "client_secret", CLIENT_SECRET );

    if ( huc.getResponseCode() == HttpURLConnection.HTTP_OK )
    {
    BufferedReader br = new BufferedReader( new InputStreamReader( huc.getInputStream(), "UTF-8" ) );

    while ( ( line = br.readLine() ) != null )
    {
        content.append( line ); 
    }
    
    JSONObject json = new JSONObject( content.toString() );
    
    System.out.println( json );
    

    }



  • With is application/x-www-form-urlencoded you will have to send this way:

     String params = "gran_type="+client_credentials+"&client_id="+CLIENT_ID+"&client_secret="+client_secret;
            byte[] post = params.getBytes( StandardCharsets.ISO_8859_1);
            URL url = new URL(URLEncoder.encode("https://api.myapi.com.br/api/oauth/token?", "ISO-8859-1"));
            HttpsURLConnection http = (HttpURLConnection) url.openConnection();
            http.setDoOutput(true);
            http.setDoInput(true);
            http.setFollowRedirects(false);
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            http.setRequestProperty("charset", "ISO-8859-1");
            http.setUseCaches(false);
    
        try(DataOutputStream output = new DataOutputStream(http.getOutputStream())){
            output.write(post);
        }
    




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2