在Java中将PayPal curl请求转换为http请求 [英] Transforming a PayPal curl request to an http request in Java

查看:2741
本文介绍了在Java中将PayPal curl请求转换为http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如,假设有调用:

  curl -v https://api.sandbox.paypal.com/v1/payments/payment \ 
-H'Content-Type: application / json'\
-H'授权:承载< 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
} :{
total:7.47,
currency:USD
}
}
]
}'

假设我有< Access-Token> 必须设置,如何将上一个字符串转换为http请求从PayPal使用Java和没有CURL的答案?



现在我对URL的HttpURLConnection做了类似下面的事情:

  private HttpURLConnection createPOSTHttpURLConnection(final URL url) throws IOException {
final HttpURLConnection connection =(HttpURLConnection)url.openConnection();

connection.setRequestMethod(POST);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);

connection.setRequestProperty(User-Agent,Mozilla / 4.0);
return connection;
}

在我的主要我做如下:

  final HttpURLConnection connection = createPOSTHttpURLConnection(url); 

connection.setRequestProperty(Authorization,Bearer< Access-Token>); //用真实值替换
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\ \\货币:美元\}}]};

connection.setFixedLengthStreamingMode(jsonData.length());

//获取POST到的输出流。
try(final DataOutputStream output = new DataOutputStream(connection.getOutputStream())){
output.writeBytes(jsonData);
output.flush();
}

final InputStream isToBeRead = connection.getInputStream();但是,我得到以下错误:


 无法从给定的URL中读取https://api.sandbox.paypal.com/v1/payments/payment与给定的参数和数据

当我尝试使用 InputStream 时会出现:

  java.net.HttpRetryException:无法在流模式下通过服务器身份验证重试
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0 HttpURLConnection.java:1636)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream HttpsURLConnectionImpl.java:254)
at com.sudengut.de.utils.url.HttpClient.readFromHttpURL(HttpClient.java:65)



UPDATE



实施我有以下结果:

 服务器返回HTTP响应代码: 400的URL:https://api.sandbox.paypal.com/v1/payments/payment 
响应代码:400
响应消息:错误请求






实施 Garry 的答案我获得以下日志:

  21:30:06.070 [main] DEBUG oahcprotocol.RequestAddCookies - 选择CookieSpec:default 
21:30:06.109 [main] DEBUG oahcprotocol.RequestAuthCache - 在上下文中未设置验证缓存
21:30:06.111 [main] DEBUG oahicPoolingHttpClientConnectionManager - route:{s} - > https://api.sandbox.paypal.com:443] [total preserved alive:0;路由分配:0 of 2;总分配:0 of 20]
21:30:06.143 [main] DEBUG oahicPoolingHttpClientConnectionManager - 连接租用:[id:0] [route:{s} - > https://api.sandbox.paypal。 com:443] [总保持活着:0;路由分配:1 of 2; total allocated:1 of 20]
21:30:06.147 [main] DEBUG oahimpl.execchain.MainClientExec - 打开连接{s} - > https://api.sandbox.paypal.com:443
21:30:06.202 [main] DEBUG oahicDefaultHttpClientConnectionOperator - 连接到api.sandbox.paypal.com/173.0.82.78:443
21:30:06.202 [main] DEBUG oahcsSSLConnectionSocketFactory - 将套接字连接到api。 sandbox.paypal.com/173.0.82.78:443 with timeout 0
21:30:06.668 [main] DEBUG oahcsSSLConnectionSocketFactory - 启用协议:[TLSv1,TLSv1.1,TLSv1.2]
21: 30:06.668 [主] DEBUG oahcsSSLConnectionSocketFactory - 启用密码套件:[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 [主] DEBUG oahcsSSLConnectionSocketFactory - 启动握手
21:30:07.291 [main] DEBUG oahcsSSLConnectionSocketFactory - 建立安全会话
21:30:07.291 [main] DEBUG oahcsSSLConnectionSocketFactory - 协商协议:TLSv1.2
21: 30:07.292 [main] DEBUG oahcsSSLConnectionSocketFactory - 协商的密码套件:TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
21:30:07.292 [main] DEBUG oahcsSSLConnectionSocketFactory - 对等体主体:CN = api.sandbox.paypal.com,OU = PayPal生产=PayPal,Inc.,L = San Jose,ST = California,C = US
21:30:07.292 [main] DEBUG oahcsSSLConnectionSocketFactory - peer alternative names:[api.sandbox.paypal.com]
21:30:07.293 [main] DEBUG oahcsSSLConnectionSocketFactory - issuer principal:CN = VeriSign 3级安全服务器CA - G3,OU =使用条款https://www.verisign.com/rpa(c)10 ,OU = VeriSign Trust Network,O =VeriSign,Inc.,C = US
21:30:07.306 [main] DEBUG oahicDefaultHttpClientConnectionOperator-建立连接192.168.178.22:45213<->173.0.82.78: 443
21:30:07.306 [main] DEBUG oahimpl.execchain.MainClientExec - 执行请求POST / v1 / payments / payment HTTP / 1.1
21:30:07.306 [main] DEBUG oahimpl.execchain .MainClientExec - 代理授权状态:UNCHALLENGED
21:30:07.310 [main] DEBUG org.apache.http.headers - http-outgoing-0> POST / v1 / payment / 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>授权:承载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>主机: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] [\\\
]
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0& > Content-Type:application / json [\r] [\\\
]
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0> Authorization:Bearer A015TlBaYzfyFSUt9rVin-Lnltn6JuQLA968RyGGC8h.Zds [\r] [\\\
]
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0> Content-Length:254 [\ r] [\\\
]
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0& Host:api.sandbox.paypal.com [\r] [\\\
]
21:30:07.311 [main] DEBUG org.apache.http.wire - http-outgoing-0> ; Connection:Keep-Alive [\r] [\\\
]
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] [\\\
]
21:30:07.311 [main] DEBUG org.apache.http.wire - http -outgoing-0> Accept-Encoding:gzip,deflate [\r] [\\\
]
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] [\\\
]
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0< 日期:Wed,29 Jul 2015 19:30:07 GMT [\r] [\\\
]
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] [\\\
]
21:30:07.664 [main] DEBUG org.apache.http.wire - http-流出-0<< Paypal-Debug-Id:3780624b824ed [\ r] [\\\
]
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0< CORRELATION-ID:3780624b824ed [\r] [\\\
]
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] [\\\
]
21:30:07.664 [main] DEBUG org.apache.http.wire - http-outgoing-0< Connection:close [\r] [\\\
]
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] [\\\
]
21:30:07.664 [main] DEBUG org .apache.http.wire - http-outgoing-0<< Vary:Authorization [\ r] [\\\
]
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:此字段名称未为此资源类型定义},{field: redirect_urls.cancel_url,issue:当payment_method为'paypal'时需要此字段}],message:请求无效 - 查看详细信息,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<<日期:Wed,29 Jul 2015 19:30:07 GMT
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0<服务器: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 = /;安全; HttpOnly
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0<< Set-Cookie:X-PP-SILOVER =; Expires = Thu,1970年1月1日00:00:01 GMT
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0< Vary:授权
21:30:07.669 [main] DEBUG org.apache.http.headers - http-outgoing-0< Content-Type:application / json
21:30:07.681 [main] DEBUG oahcpResponseProcessCookies - Cookie accepted [X-PP-SILOVER =name%3DSANDBOX3.API.1%26silo_version%3D880%26app%3Dplatformapiserv%26TIME %3D3207182677,版本:0,域:paypal.com,路径:/,到期:null]
21:30:07.684 [main] WARN oahcpResponseProcessCookies - 无效的Cookie标头:Set-Cookie:X-PP -SILOVER =; Expires = Thu,01 Jan 1970 00:00:01 GMT。无效的expires属性:Thu,01 Jan 1970 00:00:01 GMT

问题与一些更多的信息,我看到给定的cookie是附加的,不替换缺少到期日期的。只要执行:

  import java.time.Instant; 
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.HTTP;

public class GarrysSolution {

public static void main(final String [] args){

String accessToken =A-valid-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\ , \货币:美元\}}]};

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

LocalDate expirationDate = LocalDate.now()。plus(100L,ChronoUnit.DAYS);
Instant instant = Instant.from(expirationDate.atStartOfDay(ZoneId.of(GMT)));
cookie.setExpiryDate(Date.from(instant));
cookie.setCreationDate(Date.from(Instant.now()));
cookieStore.addCookie(cookie);

RequestConfig globalConfig = RequestConfig.custom()。setCookieSpec(CookieSpecs.NETSCAPE).build(); HttpClientContext上下文= HttpClientContext.create();
context.setCookieStore(cookieStore);

HttpClient httpClient = HttpClients.custom()。setDefaultRequestConfig(globalConfig)
.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,context);

System.out.println(\\\
\\\
+ context.getCookieStore()。getCookies());

System.out.println(\\\
\\\
+ httpResponse.getStatusLine()。getStatusCode()+/
+ httpResponse.getStatusLine()。getReasonPhrase );
} catch(Exception e){
System.err.println(e.getMessage());
}

}

}

,我们在上下文中看到以下cookie:

  [[version:0] [name:JSESSIONID] 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]] 
解决方案

我只是重新修改凯文的代码,删除所有的空间下JsonData变量和替换真正的令牌,它工作正常。

  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 {

//取消注释下面两行之一:
网址url =新网址(https://api.sandbox.paypal.com/v1/payments/payment);
// URL url = new URL(https://httpbin.org/post); //好用于测试

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

//将其更改为有效的令牌:
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\,\ 货币:美元\}}]};

try {
//发布数据:
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(jsonData);
output.close();

//读取响应:
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());
}
}

OUTPUT

  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 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}]}
响应代码:201
响应消息:创建


On the PayPal website, all the example calls are done using curl. Easy to repeat using CURL under Linux, but I would like to use Java to make these calls.

E.g., suppose to have the call:

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"
      }
    }
  ]
}'

Suppose that I have the value for <Access-Token> that has to be set, how can I convert the previous string into an http request to get an answer from PayPal using Java and no CURL?

Right now I did something like the following to the an HttpURLConnection to the URL:

private HttpURLConnection createPOSTHttpURLConnection(final URL url) throws IOException {
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setRequestProperty("User-Agent", "Mozilla/4.0");
        return connection;
    }

In my main I do as follows:

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();

However, I get the following error:

Cannot read from the given URL https://api.sandbox.paypal.com/v1/payments/payment with given params and data

Tha occcurs when I try to use the InputStream:

java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1636)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at com.sudengut.de.utils.url.HttpClient.readFromHttpURL(HttpClient.java:65)

UPDATE

Implementing Kevin Hoffman'solution I get the following result:

Server returned HTTP response code: 400 for URL: https://api.sandbox.paypal.com/v1/payments/payment
Response code:400
Response message:Bad Request


Implementing Garry's answer I obtain the following log:

 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

If I implement this question with some more info, I see that the given cookie is appended and doesn't replace the one with a missing expiration date. Just run:

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.HTTP;

public class GarrysSolution {

    public static void main(final String[] args) {

        String accessToken = "A-valid-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\"}}]}";

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

        LocalDate expirationDate = LocalDate.now().plus(100L, ChronoUnit.DAYS);
        Instant instant = Instant.from(expirationDate.atStartOfDay(ZoneId.of("GMT")));
        cookie.setExpiryDate(Date.from(instant));
        cookie.setCreationDate(Date.from(Instant.now()));
        cookieStore.addCookie(cookie);

        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.NETSCAPE).build();        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        HttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                                           .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, context);

            System.out.println("\n\n" + context.getCookieStore().getCookies());

            System.out.println("\n\n" + httpResponse.getStatusLine().getStatusCode() + "/"
                    + httpResponse.getStatusLine().getReasonPhrase());
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

    }

}

and we see the following cookies from the context:

[[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]]

So I guess that the problem can be solved by setting the expiration date to the proper cookie

解决方案

I just repaste the Kevin's code after removing all the spaces under the "JsonData" variable and replacing the real token and it works fine .

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());
    }
}

OUTPUT

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

这篇关于在Java中将PayPal curl请求转换为http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆