0

当我们尝试发布身份验证过程第 2 步的请求时,在向https://hamill-murazik-and-johnston6698.myshopify.com/admin/oauth/access_token发送请求时收到 http 400 错误

我们能够通过第 1 步并获得临时代码。但是当我们尝试发布 client_id、client_secret 和代码时,我们得到了 http 400 错误。

代码如下所示

public static void runTest() {
    // TODO Auto-generated method stub
    try{
    URL url = new URL("https://hamill-murazik-and-johnston6698.myshopify.com/admin/oauth/access_token");           
     HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
     String urlParameters = URLEncoder.encode("client_id", "UTF-8") + "=" + URLEncoder.encode("<CLIENT_ID", "UTF-8");
     urlParameters += "&" + URLEncoder.encode("client_secret", "UTF-8") + "=" + URLEncoder.encode("<CLIENT_SECRET", "UTF-8");
     urlParameters += "&" + URLEncoder.encode("code", "UTF-8") + "=" + URLEncoder.encode("15f01c0d8b235ffb63234c1c48822432", "UTF-8");


     /*connection.setDoInput(true);
     connection.setDoOutput(true);
     connection.setUseCaches(false);
     connection.setAllowUserInteraction(false);
     connection.setRequestProperty("Content-Length", Integer.toString(102454));
     connection.setRequestProperty("Content-Type", "text/plain");*/

     connection.setUseCaches(false);
     connection.setAllowUserInteraction(false);
     connection.setDoOutput(true);
     connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

     DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
     wr.writeBytes(urlParameters);
     wr.flush();
     wr.close();


        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
        }
        in.close();

    }catch(Exception e){
        e.printStackTrace();

    }


}
4

1 回答 1

0

我建议您使用真正的 HTTP 客户端库,例如Apache HttpClient 库。您很有可能在请求中遗漏了某些内容或编码不正确。

该库还将提供一个更简单的接口来使用,因此您只需为您的 HTTP 参数传递键值参数之类的东西,它就可以工作了。

此外,您似乎正在将您的授权请求附加到您的 URL 参数中。您需要为该请求发出 POST 请求。在您当前的实现中,您必须在 Body 中发送它,这在纯 Java 中可能会很尴尬。

我强烈建议使用 HttpClient 库,如果这对您有帮助,请告诉我们。

于 2012-10-26T15:48:37.263 回答