通过Java运行curl时为什么会失败?

时间:2020-01-23 17:37:31

标签: java curl

我正在尝试通过Java将数据发布到外部Web服务。我尝试通过HttpsURLConnection进行尝试,但是在握手时收到了一般的internal_error消息,并且在google上找不到建议来修复它。

我已经用等效的cURL脚本进行了测试,并且成功完成,没有任何问题。为了更全面地测试它,我在Java中添加了使用Process来执行该脚本的脚本。但是,相同的问题仍然存在。在运行该过程之前,我输出了整个cURL字符串,并测试了它仍在运行,并成功完成了该工作。但是,当通过Java运行时,它不能说无法解析主机,然后显示令牌字符串和其他字符。

这是替换了敏感信息的curl脚本:

curl -v -X POST %URL_HERE%
-H 'Accept: */*' 
-H 'Authorization: Bearer %LONG_STRING_HERE%' 
-H 'Content-Type: application/json' 
--data "@/Path/to/folder/file/Data_ee801ae52060.json" 

然后出现以下错误:

* About to connect() to * port 80 (#0)
*   Trying 127.0.0.1... Connection refused
* couldn't connect to host
* Closing connection #0

curl: (7) couldn't connect to host
* getaddrinfo(3) failed for Bearer:80
* Couldn't resolve host 'Bearer'
* Closing connection #0

curl: (6) Couldn't resolve host 'Bearer'
* getaddrinfo(3) failed for %TOKEN_STRING_HERE%':80
* Couldn't resolve host '%TOKEN_STRING_HERE%''
* Closing connection #0

curl: (6) Couldn't resolve host '%PARTIAL_TOKEN_STRING_HERE%.
* getaddrinfo(3) failed for application:80
* Couldn't resolve host 'application'
* Closing connection #0

curl: (6) Couldn't resolve host 'application'...

在此错误之前,它表明它正在使用端口443。 你们中有人能想到发生这种情况的原因吗?

1 个答案:

答案 0 :(得分:0)

我建议您使用PostMan https://www.getpostman.com/,该软件具有自动将curl转换为Java以及其他语言的功能。

这是使用该功能的教程:https://learning.getpostman.com/docs/postman/sending-api-requests/generate-code-snippets/

这是使用OkHttp生成示例的输出:

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "@/Path/to/folder/file/Data_ee801ae52060.json");
Request request = new Request.Builder()
  .url("%URL_HERE%")
  .method("POST", body)
  .addHeader("Accept", "/")
  .addHeader("Authorization", "Bearer %LONG_STRING_HERE%")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();