如何从Instagram API的授权URL获取代码?

时间:2019-04-29 17:01:24

标签: java instagram-api

我正在尝试从以下AuthURL的Instagram API中获取?code=xxxxxxxx参数: https://api.instagram.com/oauth/authorize/?client_id=18425222ebe44b71b09b293fb771c69f&redirect_uri=https%3A%2F%2Ffresh-air.cloud&response_type=code&scope=likes comments

在浏览器(例如chrome)中执行此链接时,?code=xxxxxxxx参数将附加到redirect_uri,但是我需要使用Java以编程方式获取此代码。

我尝试了以下方法:

private String getVerifierCode(String authUrl) {
 try {
  URL url = new URL(authUrl);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
  con.setRequestMethod("GET");
  con.setRequestProperty("Content-Type", "application/json");
  con.setConnectTimeout(5000);
  con.setReadTimeout(5000);
  con.setInstanceFollowRedirects(true);
  System.out.println(getFullResponse(con));
 } catch (Throwable th) {
  th.printStackTrace();
 }
 return null;
}

private String getFullResponse(HttpURLConnection con) throws IOException {
 StringBuilder fullResponseBuilder = new StringBuilder();

 fullResponseBuilder.append(con.getResponseCode())
  .append(" ")
  .append(con.getResponseMessage())
  .append("\n");

 con.getHeaderFields()
  .entrySet()
  .stream()
  .filter(entry -> entry.getKey() != null)
  .forEach(entry -> {

   fullResponseBuilder.append(entry.getKey())
   .append(": ");

   List < String > headerValues = entry.getValue();
   Iterator < String > it = headerValues.iterator();
   if (it.hasNext()) {
    fullResponseBuilder.append(it.next());

    while (it.hasNext()) {
     fullResponseBuilder.append(", ")
      .append(it.next());
    }
   }

   fullResponseBuilder.append("\n");
  });

 Reader streamReader = null;

 if (con.getResponseCode() > 299) {
  streamReader = new InputStreamReader(con.getErrorStream());
 } else {
  streamReader = new InputStreamReader(con.getInputStream());
 }

 BufferedReader in = new BufferedReader(streamReader);
 String inputLine;
 StringBuilder content = new StringBuilder();
 while ((inputLine = in .readLine()) != null) {
  content.append(inputLine);
 }

 in .close();

 fullResponseBuilder.append("Response: ")
  .append(content);

 return fullResponseBuilder.toString();
}

否则会导致400错误的请求状态代码:

400 Bad Request
Connection: close
Content-Length: 105
Date: Mon, 29 Apr 2019 16:46:16 GMT
Content-Type: text/html; charset=utf-8
Response: <html><head><title>5xx Server Error</title></head><body><h1>5xx Server Error</h1></body></html>

是否有办法获取?code=xxxxxxxx参数?

0 个答案:

没有答案