I'm trying to get a token for the reddit api using java. There are a ton of examples out there using Python so I figured I'd simply translate one to java. Clearly that wasn't so simple.
This is the java code
HttpPost httppost = new HttpPost("https://www.reddit.com/api/v1/access_token");
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("CLIENT ID", "API SECRET KEY");
provider.setCredentials(AuthScope.ANY, credentials);
List<NameValuePair> nvps = new ArrayList<>(3);
nvps.add(new BasicNameValuePair("grant_type", "password"));
nvps.add(new BasicNameValuePair("username", "MY USERNAME"));
nvps.add(new BasicNameValuePair("password", "MY PASSWORD"));
StringEntity strEntity = new StringEntity(URLEncodedUtils.format(nvps, StandardCharsets.UTF_8), ContentType.APPLICATION_FORM_URLENCODED);
httppost.setEntity(strEntity);
httppost.addHeader("User-Agent", "MyBot/0.0.1");
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build();
CloseableHttpResponse response = httpClient.execute(httppost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
This results in a 5xx server error, which you can see below.
<html>
<head>
<title>Internal Server Error</title>
</head>
<body>
<h1>Internal Server Error</h1>
</body>
</html>
Comparing this with the Python version
import requests
auth = requests.auth.HTTPBasicAuth('CLIENT ID', 'API SECRET KEY')
data = {'grant_type': 'password',
'username': 'MY USERNAME',
'password': 'MY PASSWORD'}
headers = {'User-Agent': 'MyBot/0.0.1'}
res = requests.post('https://www.reddit.com/api/v1/access_token',
auth=auth, data=data, headers=headers)
TOKEN = res.json()['access_token']
headers = {**headers, **{'Authorization': f"bearer {TOKEN}"}}
requests.get('https://oauth.reddit.com/api/v1/me', headers=headers)
Results in a completed request with the token.
CodePudding user response:
Just change the entity from:
StringEntity strEntity = new StringEntity(URLEncodedUtils.format(nvps, StandardCharsets.UTF_8),ContentType.APPLICATION_FORM_URLENCODED);
To
StringEntity strEntity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
And after long time no use HttpClient, I know why I've switched to okHttp