curl命令等效于java

这是我的curl命令:

curl https://login.xyz.com/v1/oauth/token -H "Accept:
application/json" --data 'client_id=client_id' --data
'client_secret=client_secret' --data 'redirect_uri=redirect_uri'
--data 'code=code'

我试图在java中发布它.这是我想要做的:

String resourceUrl = "https://login.xyz.com/v1/oauth/token?client_id=<client.id>&client_secret=<client.secret>&redirect_uri=https://login.xyz.com/user/login&code=<code>";
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(resourceUrl).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();      
System.out.println(httpcon.getHeaderField(0));

但我得到HTTP / 1.1 500内部服务器错误

最佳答案 我没有测试,只是通过查看文档和源代码,我可以看到你的curl命令和Java实现之间的一些区别:

卷曲:

>执行POST
> Content-Type是application / x-www-form-urlencoded

Curl manpage

-d, –data

(HTTP) Sends the specified data in a POST request to the HTTP server,
in the same way that a browser does when a user has filled in an HTML
form and presses the submit button. This will cause curl to pass the
data to the server using the content-type
application/x-www-form-urlencoded. Compare to -F, –form.

另见:How are parameters sent in an HTTP POST request?

Java实现:

>执行POST但URL是GET相似的(您将请求方法设置为POST但是您在URL查询字符串中传递参数)
> Content-Type是application / json

我希望这有帮助.

点赞