我正在尝试通过向 {{3>发出 POST 请求来获取访问令牌和刷新令牌 } 端点。
我关注了“https://login.eloqua.com/auth/oauth2/token”文档(资源所有者密码凭据授权流程)。
我尝试了以下代码,并且在“conn.getInputStream()”时响应代码为411(即内容长度问题)。我已经添加了内容长度。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class EloquaOath2App {
public static void main(String[] args) {
String siteName = "MarketingCloud08";
String username = "myAccountUsername";
String password = "myPassword";
String uri = "https://login.eloqua.com/auth/oauth2/token";
String client_id = "my-app-client-id";
String client_secret = "my-app-client-secret";
String authString = client_id + ":" + client_secret;// format is client_id:client_secret
String headerAuthorization = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());
String userAndSite = siteName + "\\" + username;
String response = null;
try {
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", headerAuthorization);
conn.setRequestProperty("grant_type", "password");
conn.setRequestProperty("scope", "full");
conn.setRequestProperty("username", userAndSite); // The user’s sitename and username in the form sitename + '/' + username
conn.setRequestProperty("password", password);
byte[] postData = uri.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
System.out.println("postDataLength :" + postDataLength);
if (postDataLength > 0) {
// In case that the content is not empty
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
} else {
// In case that the content is not empty
conn.setRequestProperty("Content-Length", "0");
}
conn.setDoOutput(true);
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response += line;
System.out.println(response);
}
rd.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
异常日志是:
java.io.IOException: Server returned HTTP response code: 411 for URL: https://login.eloqua.com/auth/oauth2/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.nextrow.aem.eloquaconnector.core.models.EloquaOath2Test.main(EloquaOath2App.java:61)
预期输出如下:
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKW"
}
请指导我并就此提出建议/答案。
谢谢,
Arpit
答案 0 :(得分:0)
在阅读之前,你必须给连接写点东西。
conn.getOutputStream().write(postData);
并且还要注意grant_type,scope等必须作为请求体传递,而不是作为http头传递。使用邮递员或类似的东西来做一些测试请求来休息api。