簡體   English   中英

將Paypal curl獲取訪問令牌請求轉換為Java中的http請求

[英]Transform paypal curl get access token request into an http request in Java

我正在嘗試獲取訪問令牌,但它給出401 Unauthorize錯誤,但在curl中使用相同的clientid和secret可以正常工作。 請參見下面的代碼,我嘗試使用DataConverter將客戶端和密鑰轉換為base 64,但遇到相同的輸出。

    try {

        String u = <client id>;
        String p = <secret>;
        String tokenInput = "grant_type=client_credentials";
        System.setProperty("https.protocols", "TLSv1.1,TLSv1.2,SSLv3,SSLv2Hello");
java.net.URL url = new java.net.URL("https://api.sandbox.paypal.com/v1/oauth2/token");
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();

String up = u + ":" + p;

//String r = new String(javax.xml.bind.DatatypeConverter.parseBase64Binary(u));
//String s = new String(javax.xml.bind.DatatypeConverter.parseBase64Binary(p));

conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + up);
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(tokenInput.length()));
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Accept-Language", "en_US");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setUseCaches(false);
conn.setDoOutput(true);

    java.io.DataOutputStream output = new java.io.DataOutputStream(conn.getOutputStream());
    output.write(tokenInput.getBytes());
    output.close();

    // Read the response:
    java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();

System.out.println("Response code:" + conn.getResponseCode());
System.out.println("Response message:" + conn.getResponseMessage());

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
}

也許已經有點晚了,但是我遇到了同樣的問題,有人可能也需要這個。

對我來說,它可以對client_id進行編碼並使用Base64進行加密

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        String up = u + ":" + p;

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Basic " + new String(new org.apache.commons.codec.binary.Base64().encode(up.getBytes())));
        conn.setRequestProperty("Content-Length", Integer.toString(tokenInput.length()));
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Accept-Language", "en_US");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM