Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中将PayPal curl请求转换为http请求_Java_Http_Curl_Paypal - Fatal编程技术网

在Java中将PayPal curl请求转换为http请求

在Java中将PayPal curl请求转换为http请求,java,http,curl,paypal,Java,Http,Curl,Paypal,在PayPal网站上,所有示例调用都是使用curl完成的。在Linux下使用CURL很容易重复,但我想使用Java来进行这些调用 例如,假设打电话: curl -v https://api.sandbox.paypal.com/v1/payments/payment \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer <Access-Token>' \ -d '{ "intent":"sale",

在PayPal网站上,所有示例调用都是使用curl完成的。在Linux下使用CURL很容易重复,但我想使用Java来进行这些调用

例如,假设打电话:

curl -v https://api.sandbox.paypal.com/v1/payments/payment \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <Access-Token>' \
-d '{
  "intent":"sale",
  "redirect_urls":{
    "return_url":"http://example.com/your_redirect_url.html",
    "cancel_url":"http://example.com/your_cancel_url.html"
  },
  "payer":{
    "payment_method":"paypal"
  },
  "transactions":[
    {
      "amount":{
        "total":"7.47",
        "currency":"USD"
      }
    }
  ]
}'
我的主要工作如下:

final HttpURLConnection connection = createPOSTHttpURLConnection(url);

connection.setRequestProperty("Authorization", "Bearer <Access-Token>");//replaced with a real value
connection.setRequestProperty("Content-Type", "application/json");
        final String jsonData = "{ \"intent\":\"sale\",  \"redirect_urls\":{    \"return_url\":\"http://example.com/your_redirect_url.html\",    \"cancel_url\":\"http://example.com/your_cancel_url.html\" }, \"payer\":{    \"payment_method\":\"paypal\"  },  \"transactions\":[    {      \"amount\":{        \"total\":\"7.47\",        \"currency\":\"USD\"}}]}";

connection.setFixedLengthStreamingMode(jsonData.length());

// get the output stream to POST to.
try(final DataOutputStream output = new DataOutputStream(connection.getOutputStream())) {
        output.writeBytes(jsonData);
        output.flush();
}

final InputStream isToBeRead =  connection.getInputStream();
当我尝试使用InputStream时会发生这种情况:

使现代化 实施“解决方案”,我得到以下结果:

Server returned HTTP response code: 400 for URL: https://api.sandbox.paypal.com/v1/payments/payment
Response code:400
Response message:Bad Request
实施者的回答我获得以下日志:

 21:30:06.070 [main] DEBUG o.a.h.c.protocol.RequestAddCookies - CookieSpec selected: default
21:30:06.109 [main] DEBUG o.a.h.c.protocol.RequestAuthCache - Auth cache not set in the context
21:30:06.111 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection request: [route: {s}->https://api.sandbox.paypal.com:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
21:30:06.143 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {s}->https://api.sandbox.paypal.com:443][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
21:30:06.147 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Opening connection {s}->https://api.sandbox.paypal.com:443
21:30:06.202 [main] DEBUG o.a.h.i.c.DefaultHttpClientConnectionOperator - Connecting to api.sandbox.paypal.com/173.0.82.78:443
21:30:06.202 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Connecting socket to api.sandbox.paypal.com/173.0.82.78:443 with timeout 0
21:30:06.668 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Enabled protocols: [TLSv1, TLSv1.1, TLSv1.2]
21:30:06.668 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Enabled cipher suites:[TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
21:30:06.669 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Starting handshake
21:30:07.291 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Secure session established
21:30:07.291 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -  negotiated protocol: TLSv1.2
21:30:07.292 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -  negotiated cipher suite: TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
21:30:07.292 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -  peer principal: CN=api.sandbox.paypal.com, OU=PayPal Production, O="PayPal, Inc.", L=San Jose, ST=California, C=US
21:30:07.292 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -  peer alternative names: [api.sandbox.paypal.com]
21:30:07.293 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -  issuer principal: CN=VeriSign Class 3 Secure Server CA - G3, OU=Terms of use at https://www.verisign.com/rpa (c)10, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
21:30:07.306 [main] DEBUG o.a.h.i.c.DefaultHttpClientConnectionOperator - Connection established 192.168.178.22:45213<->173.0.82.78:443
21:30:07.306 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Executing request POST /v1/payments/payment HTTP/1.1
21:30:07.306 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
21:30:07.310 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> POST /v1/payments/payment HTTP/1.1
21:30:07.310 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Type: application/json
21:30:07.310 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Authorization: Bearer A015TlBaYzfyFSUt9rVin-Lnltn6JuQLA968RyGGC8h.Zds
21:30:07.310 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Length: 254
21:30:07.311 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: api.sandbox.paypal.com
21:30:07.311 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
21:30:07.311 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5 (Java/1.8.0_25)
21:30:07.311 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /v1/payments/payment HTTP/1.1[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/json[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Authorization: Bearer A015TlBaYzfyFSUt9rVin-Lnltn6JuQLA968RyGGC8h.Zds[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Length: 254[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: api.sandbox.paypal.com[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5 (Java/1.8.0_25)[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
21:30:07.312 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "{ "intent":"sale","redirect_urls":{ "return_url":"http://example.com/your_redirect_url.html", "cancel_url ":"http://example.com/your_cancel_url.html" }, "payer":{"payment_method":"paypal"},"transactions":[{ "amount":{ "total":"7.47", "currency":"USD"}}]}"
21:30:07.663 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 400 Bad Request[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Date: Wed, 29 Jul 2015 19:30:07 GMT[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Server: Apache[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "PROXY_SERVER_INFO: host=slcsbplatformapiserv3001.slc.paypal.com;threadId=205[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Paypal-Debug-Id: 3780624b824ed[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "CORRELATION-ID: 3780624b824ed[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Language: *[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Connection: close[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Connection: close[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Length: 404[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D880%26app%3Dplatformapiserv%26TIME%3D3207182677; domain=.paypal.com; path=/; Secure; HttpOnly[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Vary: Authorization[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Type: application/json[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "{"name":"VALIDATION_ERROR","details":[{"field":"redirect_urls.cancel_url ","issue":"This field name is not defined for this resource type"},{"field":"redirect_urls.cancel_url","issue":"This field required when payment_method is 'paypal'"}],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#VALIDATION_ERROR","debug_id":"3780624b824ed"}"
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 400 Bad Request
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Wed, 29 Jul 2015 19:30:07 GMT
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Server: Apache
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << PROXY_SERVER_INFO: host=slcsbplatformapiserv3001.slc.paypal.com;threadId=205
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Paypal-Debug-Id: 3780624b824ed
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << CORRELATION-ID: 3780624b824ed
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Language: *
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Connection: close
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Connection: close
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Length: 404
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D880%26app%3Dplatformapiserv%26TIME%3D3207182677; domain=.paypal.com; path=/; Secure; HttpOnly
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Vary: Authorization
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: application/json
21:30:07.681 [main] DEBUG o.a.h.c.p.ResponseProcessCookies - Cookie accepted [X-PP-SILOVER="name%3DSANDBOX3.API.1%26silo_version%3D880%26app%3Dplatformapiserv%26TIME%3D3207182677", version:0, domain:paypal.com, path:/, expiry:null]
21:30:07.684 [main] WARN  o.a.h.c.p.ResponseProcessCookies - Invalid cookie header: "Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT". Invalid 'expires' attribute: Thu, 01 Jan 1970 00:00:01 GMT
我们从上下文中看到以下cookies:

[[version: 0][name: JSESSIONID][value: 1234][domain: .paypal.com][path: /][expiry: Fri Nov 06 01:00:00 CET 2015], [version: 0][name: X-PP-SILOVER][value: name%3DSANDBOX3.API.1%26silo_version%3D880%26app%3Dplatformapiserv%26TIME%3D2370156885][domain: .paypal.com][path: /][expiry: null]]

因此,我想通过将过期日期设置为正确的cookie可以解决这个问题。代码在try块中吞咽异常,没有抛出表示发生HTTP错误的捕获。这可能是由于无效的访问令牌造成的。然后,代码尝试读取HTTP响应,但由于401错误导致没有响应,因此读取失败,并抛出正在打印到屏幕上的异常

在您设置代码时,访问令牌是否可能已过期

我获得了下面的代码,使用有效的访问令牌成功地与PayPal合作。与您的代码有一些细微的区别,没有单独的方法;使用HttpsURLConnection而不是HttpUrlConnection;删除了一些不需要的标题;等等,但是这些改变都不能单独起作用——他们只是把它收紧了一点,确保它在出错时打印出正确的错误消息。然后,一旦我提供了一个有效的访问令牌,它就成功地工作了。我猜想您已经意识到访问令牌周围的尖括号必须移除,否则您将永远无法使用curl方法

另外,请记住,这只是示例代码—生产代码应该将close语句移动到finally块中,或者返回到最初使用的try with resources方法

import java.io.BufferedReader; 
import java.io.InputStreamReader;
import java.io.DataOutputStream; 
import java.net.URL;             
import javax.net.ssl.HttpsURLConnection;

public class TestHttpsPost {

    public static void main(String[] args) throws Exception {

        // Uncomment one of these next two lines:
        URL url = new URL("https://api.sandbox.paypal.com/v1/payments/payment");
        //URL url = new URL("https://httpbin.org/post"); // good for testing

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Change this to a valid token:
        connection.setRequestProperty("Authorization", "Bearer <Access-Token>");
        connection.setRequestProperty("Content-Type", "application/json");
        String jsonData = "{ \"intent\":\"sale\",  \"redirect_urls\":{        \"return_url\":\"http://example.com/your_redirect_url.html\",    \"cancel_url    \":\"http://example.com/your_cancel_url.html\" }, \"payer\":{    \"payment_method\":\"paypal\"  },  \"transactions\":[    {          \"amount\":{        \"total\":\"7.47\",        \"currency\":\"USD\"}}]}";

        try {
            // Post the data:
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(jsonData);
            output.close();

            // Read the response:
            BufferedReader reader = new BufferedReader(new InputStreamReader(
              connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

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

代码正在try块中吞咽异常,没有抛出表示发生HTTP错误的捕获。这可能是由于无效的访问令牌造成的。然后,代码尝试读取HTTP响应,但由于401错误导致没有响应,因此读取失败,并抛出正在打印到屏幕上的异常

在您设置代码时,访问令牌是否可能已过期

我获得了下面的代码,使用有效的访问令牌成功地与PayPal合作。与您的代码有一些细微的区别,没有单独的方法;使用HttpsURLConnection而不是HttpUrlConnection;删除了一些不需要的标题;等等,但是这些改变都不能单独起作用——他们只是把它收紧了一点,确保它在出错时打印出正确的错误消息。然后,一旦我提供了一个有效的访问令牌,它就成功地工作了。我猜想您已经意识到访问令牌周围的尖括号必须移除,否则您将永远无法使用curl方法

另外,请记住,这只是示例代码—生产代码应该将close语句移动到finally块中,或者返回到最初使用的try with resources方法

import java.io.BufferedReader; 
import java.io.InputStreamReader;
import java.io.DataOutputStream; 
import java.net.URL;             
import javax.net.ssl.HttpsURLConnection;

public class TestHttpsPost {

    public static void main(String[] args) throws Exception {

        // Uncomment one of these next two lines:
        URL url = new URL("https://api.sandbox.paypal.com/v1/payments/payment");
        //URL url = new URL("https://httpbin.org/post"); // good for testing

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Change this to a valid token:
        connection.setRequestProperty("Authorization", "Bearer <Access-Token>");
        connection.setRequestProperty("Content-Type", "application/json");
        String jsonData = "{ \"intent\":\"sale\",  \"redirect_urls\":{        \"return_url\":\"http://example.com/your_redirect_url.html\",    \"cancel_url    \":\"http://example.com/your_cancel_url.html\" }, \"payer\":{    \"payment_method\":\"paypal\"  },  \"transactions\":[    {          \"amount\":{        \"total\":\"7.47\",        \"currency\":\"USD\"}}]}";

        try {
            // Post the data:
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(jsonData);
            output.close();

            // Read the response:
            BufferedReader reader = new BufferedReader(new InputStreamReader(
              connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

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

您可能希望尝试Apache HTTPClient,如下所示:

BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".paypal.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);

String accessToken = "your_access_token";
String jsonString = "{ \"intent\":\"sale\",\"redirect_urls\":{ \"return_url\":\"http://example.com/your_redirect_url.html\", \"cancel_url \":\"http://example.com/your_cancel_url.html\" }, \"payer\":{\"payment_method\":\"paypal\"},\"transactions\":[{ \"amount\":{ \"total\":\"7.47\", \"currency\":\"USD\"}}]}";
HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
HttpPost httpPost = new HttpPost("https://api.sandbox.paypal.com/v1/payments/payment");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + accessToken);
StringEntity entity = new StringEntity(jsonString, HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    System.out.println(httpResponse.getStatusLine().getStatusCode() + "/" + httpResponse.getStatusLine().getReasonPhrase());
} catch (Exception e) {
    System.err.println(e.getMessage());
}

您可能希望尝试Apache HTTPClient,如下所示:

BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".paypal.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);

String accessToken = "your_access_token";
String jsonString = "{ \"intent\":\"sale\",\"redirect_urls\":{ \"return_url\":\"http://example.com/your_redirect_url.html\", \"cancel_url \":\"http://example.com/your_cancel_url.html\" }, \"payer\":{\"payment_method\":\"paypal\"},\"transactions\":[{ \"amount\":{ \"total\":\"7.47\", \"currency\":\"USD\"}}]}";
HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
HttpPost httpPost = new HttpPost("https://api.sandbox.paypal.com/v1/payments/payment");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + accessToken);
StringEntity entity = new StringEntity(jsonString, HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    System.out.println(httpResponse.getStatusLine().getStatusCode() + "/" + httpResponse.getStatusLine().getReasonPhrase());
} catch (Exception e) {
    System.err.println(e.getMessage());
}

在删除JsonData变量下的所有空格并替换真正的令牌之后,我只是重新编写了Kevin的代码,它工作得很好

import java.io.BufferedReader; 
import java.io.InputStreamReader;
import java.io.DataOutputStream; 
import java.net.URL;             
import javax.net.ssl.HttpsURLConnection;

public class TestHttpsPost {

    public static void main(String[] args) throws Exception {

        // Uncomment one of these next two lines:
        URL url = new URL("https://api.sandbox.paypal.com/v1/payments/payment");
        //URL url = new URL("https://httpbin.org/post"); // good for testing

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Change this to a valid token:
        connection.setRequestProperty("Authorization", "Bearer A015mK--1cz4kfmrLwEuxE9VgHIh9IwEqNvUvdlqMAByvjI");
        connection.setRequestProperty("Content-Type", "application/json");
        String jsonData = "{ \"intent\":\"sale\",\"redirect_urls\":{\"return_url\":\"http://example.com/your_redirect_url.html\",\"cancel_url\":\"http://example.com/your_cancel_url.html\"},\"payer\":{\"payment_method\":\"paypal\"},\"transactions\":[{\"amount\":{\"total\":\"7.47\",\"currency\":\"USD\"}}]}";

        try {
            // Post the data:
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(jsonData);
            output.close();

            // Read the response:
            BufferedReader reader = new BufferedReader(new InputStreamReader(
              connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Response code:" + connection.getResponseCode());
        System.out.println("Response message:" + connection.getResponseMessage());
    }
}
输出


在删除JsonData变量下的所有空格并替换真正的令牌之后,我只是重新编写了Kevin的代码,它工作得很好

import java.io.BufferedReader; 
import java.io.InputStreamReader;
import java.io.DataOutputStream; 
import java.net.URL;             
import javax.net.ssl.HttpsURLConnection;

public class TestHttpsPost {

    public static void main(String[] args) throws Exception {

        // Uncomment one of these next two lines:
        URL url = new URL("https://api.sandbox.paypal.com/v1/payments/payment");
        //URL url = new URL("https://httpbin.org/post"); // good for testing

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Change this to a valid token:
        connection.setRequestProperty("Authorization", "Bearer A015mK--1cz4kfmrLwEuxE9VgHIh9IwEqNvUvdlqMAByvjI");
        connection.setRequestProperty("Content-Type", "application/json");
        String jsonData = "{ \"intent\":\"sale\",\"redirect_urls\":{\"return_url\":\"http://example.com/your_redirect_url.html\",\"cancel_url\":\"http://example.com/your_cancel_url.html\"},\"payer\":{\"payment_method\":\"paypal\"},\"transactions\":[{\"amount\":{\"total\":\"7.47\",\"currency\":\"USD\"}}]}";

        try {
            // Post the data:
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(jsonData);
            output.close();

            // Read the response:
            BufferedReader reader = new BufferedReader(new InputStreamReader(
              connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Response code:" + connection.getResponseCode());
        System.out.println("Response message:" + connection.getResponseMessage());
    }
}
输出


不用说,使用CURL时,一切都很好,JSON以一个“不应该”开头——该引号在CURL请求中用作shell参数分隔符,不随数据一起传递。在发送数据之前,您应该考虑使用JSON库验证/格式化数据。是的,但同时删除不必要的字符,我也会遇到同样的错误。@heeneee我强烈反对!用“使用库”来回答编程问题是什么建议?!?我不认为这符合StackOverflow的精神。所以,如果我问如何在Java 7中实现一个函数,你的标准答案是使用Guava。当然,你有权不同意,但你的目标是使用Java与PayPal交互。PayPal提供了一个库来实现这一点。你为什么不使用它呢?不用说,对于CURL,一切都很好,你的JSON以一个“不应该”开头——这个引号在CURL请求中用作shell参数分隔符,并且不随数据一起传递。在发送数据之前,您应该考虑使用JSON库验证/格式化数据。是的,但同时删除不必要的字符,我也会遇到同样的错误。@heeneee我强烈反对!用“使用库”来回答编程问题是什么建议?!?我不认为这符合StackOverflow的精神。所以,如果我问如何小鬼

在Java7中,你的标准答案是使用番石榴。当然,你有权不同意,但你的目标是使用Java与PayPal交互。PayPal提供了一个库来实现这一点。为什么不使用它呢?我想我会使用PayPal SDK,但我想让这个例子起作用。所以,我做了以下几点。1我请求获得一个有效的令牌,回答是Bearer tokenvalue;2我用给定的令牌重复了你的测试;3输出为:服务器为URL返回HTTP响应代码:400:https://api.sandbox.paypal.com/v1/payments/payment 响应代码:400响应消息:错误的请求我同意SDK可能是一种更好的方式,我不确定为什么这个代码对你不起作用-我可以在这里很好地运行它-我被难住了。嗯,我可以使用PayPal SDK进行调用,但仍然无法使用UrlConnection或HttpClient。我的意思是,我可能会忘记这种方法,但我想知道这里出了什么问题。我想我会使用PayPal SDK,但我想让这个例子起作用。所以,我做了以下几点。1我请求获得一个有效的令牌,回答是Bearer tokenvalue;2我用给定的令牌重复了你的测试;3输出为:服务器为URL返回HTTP响应代码:400:https://api.sandbox.paypal.com/v1/payments/payment 响应代码:400响应消息:错误的请求我同意SDK可能是一种更好的方式,我不确定为什么这个代码对你不起作用-我可以在这里很好地运行它-我被难住了。嗯,我可以使用PayPal SDK进行调用,但仍然无法使用UrlConnection或HttpClient。我的意思是,我可能会忘记这种方法,但我想了解这里出了什么问题。我发布了使用您的解决方案获得的结果。我怀疑还有什么东西不见了。我不能让CURL工作而Java代码不工作。奇怪的最新版本,即第4版。5@mat_boy .. 好吧,看来是饼干的问题。我已更新答案以添加自定义cookies。请尝试此操作。我已更新输出。你确定这是设置cookie的正确方法吗?我想问题出在我的Spring Boot应用程序上。请看,我发布了使用您的解决方案获得的结果。我怀疑还有什么东西不见了。我不能让CURL工作而Java代码不工作。奇怪的最新版本,即第4版。5@mat_boy .. 好吧,看来是饼干的问题。我已更新答案以添加自定义cookies。请尝试此操作。我已更新输出。你确定这是设置cookie的正确方法吗?我想问题出在我的Spring Boot应用程序上。看吧,最后的问题是JSON,哈哈。没错,现在可以了。非常感谢!干得好,伊珊-真希望我能试一下!所以,最后的问题是JSON,哈哈。没错,现在可以了。非常感谢!干得好,伊珊-真希望我能试一下!
import java.io.BufferedReader; 
import java.io.InputStreamReader;
import java.io.DataOutputStream; 
import java.net.URL;             
import javax.net.ssl.HttpsURLConnection;

public class TestHttpsPost {

    public static void main(String[] args) throws Exception {

        // Uncomment one of these next two lines:
        URL url = new URL("https://api.sandbox.paypal.com/v1/payments/payment");
        //URL url = new URL("https://httpbin.org/post"); // good for testing

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Change this to a valid token:
        connection.setRequestProperty("Authorization", "Bearer A015mK--1cz4kfmrLwEuxE9VgHIh9IwEqNvUvdlqMAByvjI");
        connection.setRequestProperty("Content-Type", "application/json");
        String jsonData = "{ \"intent\":\"sale\",\"redirect_urls\":{\"return_url\":\"http://example.com/your_redirect_url.html\",\"cancel_url\":\"http://example.com/your_cancel_url.html\"},\"payer\":{\"payment_method\":\"paypal\"},\"transactions\":[{\"amount\":{\"total\":\"7.47\",\"currency\":\"USD\"}}]}";

        try {
            // Post the data:
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(jsonData);
            output.close();

            // Read the response:
            BufferedReader reader = new BufferedReader(new InputStreamReader(
              connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Response code:" + connection.getResponseCode());
        System.out.println("Response message:" + connection.getResponseMessage());
    }
}
C:\Users\Desktop\Java>java TestHttpsPost
{"id":"PAY-0SM99950896487827KW4ZAZA","create_time":"2015-07-30T02:48:04Z","updat
e_time":"2015-07-30T02:48:04Z","state":"created","intent":"sale","payer":{"payme
nt_method":"paypal","payer_info":{"shipping_address":{}}},"transactions":[{"amou
nt":{"total":"7.47","currency":"USD","details":{"subtotal":"7.47"}},"related_res
ources":[]}],"links":[{"href":"https://api.sandbox.paypal.com/v1/payments/paymen
t/PAY-0SM99950896487827KW4ZAZA","rel":"self","method":"GET"},{"href":"https://ww
w.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-8F164253W5887
9412","rel":"approval_url","method":"REDIRECT"},{"href":"https://api.sandbox.pay
pal.com/v1/payments/payment/PAY-0SM99950896487827KW4ZAZA/execute","rel":"execute
","method":"POST"}]}
Response code:201
Response message:Created