Problems generating OAuth access token with HttpURLConnection

0

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

NOTE: I did the same procedure for the terminal using curl and the data was generated normally.

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 );
}
    
asked by anonymous 16.01.2018 / 19:28

1 answer

0

With it's application / x-www-form-urlencoded you will have to send it 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);
        }
    
17.01.2018 / 13:47