[英]Java How to send properly body in request
我尝试通过用Java编写的控制台程序与API连接,但是每次都会遇到400个错误请求。
curl -X POST \
'https://allegro.pl/auth/oauth/device' \
-H 'Authorization: Basic base64(client_id:client_secret)' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'client_id={client_id}'
import java.io.*;
import java.net.*;
import java.util.Base64;
public class AccessToken {
void getAccessToken() throws IOException {
String authUrl = "https://allegro.pl.allegrosandbox.pl/auth/oauth/device";
String userCredentials = "bdc22d4054c04090ae687d4e0e75a7b4:uNHKzbWhwWQYneraAU7yVWHIdLSIw7MmCHkliZOyk7QNeYeRANdQuApJqFNkADcy";
String basicAuth = Base64.getEncoder().encodeToString(userCredentials.getBytes());
HttpURLConnection myURL = (HttpURLConnection) new URL(authUrl).openConnection();
myURL.setRequestProperty("Request Method", "POST");
myURL.setRequestProperty("Authorization", "Basic " + basicAuth);
myURL.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURL.setDoOutput(true);
OutputStream outStream = myURL.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write("client_id={bdc22d4054c04090ae687d4e0e75a7b4}");
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();
int status = myURL.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response (Code):" + status);
System.out.println("Response (Message):" + myURL.getResponseMessage());
}
}
使用JaxB
/ JaxRS
/**
* OAuth2 / OIDC token retrieval response.
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class OAuthServerResponse
{
@XmlElement(name = "access_token")
private String access_token;
@XmlElement(name = "refresh_token")
private String refresh_token;
@XmlElement(name = "token_type")
private String token_type;
@XmlElement(name = "scope")
private String scope;
@XmlElement(name = "tenant")
private String tenant;
@XmlElement(name = "id_token")
private String id_token;
// empty constructor, getters, setters
}
private com.sun.jersey.api.client.WebResource webResource;
public void init()
{
webResource = Client.create().resource(authorizationServerRoot + "/" + tokenEndpoint);
}
/**
* retrieve an access token against the current authorization server
*
* @param payload the request payload as String
* @return an access token
*/
public OAuthServerResponse getAccessToken(String payload)
{
OAuthServerResponse result = null;
final ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, payload);
if (response.getStatus() == HttpStatus.SC_OK)
{
result = response.getEntity(OAuthServerResponse.class);
}
else
{
LOG.error(String.format("%d invalid oauth2 request", response.getStatus()));
}
return result;
}
有效负载看起来像: "grant_type=client_credentials&client_id=foo&client_secret=bar"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.