将paypal curl转换为Java中的http请求

时间:2017-05-05 07:28:37

标签: java paypal https

我正在尝试获取访问令牌,但它提供了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();
    } 
}

1 个答案:

答案 0 :(得分:0)

也许有点晚了,但我遇到了同样的问题,有人可能也需要这个。

对我来说,它可以对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);