java - 尝试使用Java Http URL连接来执行curl命令

标签 java http curl

嗨,我有以下curl脚本

curl -i -X PUT -d "{\"loginList\":[{\"externalLoginKey\":\"1406560803453iGBoMm\",\"testStatus\":\"R\"}]}" -H "X-test-debug-override: true" -k  http://someapi/logins

我正在尝试使用 java 进行 Http post。以下是我的代码。难道我做错了什么?我收到错误,但curl 运行良好

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpTesting {

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

    String apiURL = "http://someapi/logins";
    URL url = new URL(apiURL);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    String str = "{\"loginList\":[{\"externalLoginKey\":\"1406565099034jZrHXe\",\"testStatus\":\"R\"}]}";
    con.disconnect();

    con.setDoOutput(true);
    con.setDoInput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("X-test-debug-override", "true");
    con.connect();

    OutputStream outStream = con.getOutputStream();
    DataOutputStream out = new DataOutputStream(outStream);
    out.writeBytes(str);
    out.flush();
    out.close();

    int responseCode = con.getResponseCode();
    System.out.println(responseCode);

}

}

最佳答案

来自curl man page :

-d, --data <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.

(强调我的。)

即使您发送 JSON,您的 Content-Type 也需要为 “application/x-www-form-urlencoded”。这意味着您还需要使用 URLEncoder 对数据进行编码:

out.writeBytes(URLEncoder.encode(str, "UTF-8"));

顺便说一句,您的 curl 命令使用 PUT 方法,而 Java 代码使用 "POST" 方法。

关于java - 尝试使用Java Http URL连接来执行curl命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25000708/

相关文章:

java - 我可以使用多个 try catch block 来抛出多个错误或异常吗

java - 如何使用 .hasMoreElements() 循环 JButtonGroup?

Java - map 允许空值/键而不是线程安全的

java - PowerMockito 的 UnfinishedStubbingException

php - 使用 Volley 发送 post 请求并在 PHP 中接收

PHP Curl 未连接到 HTTPS

http - 如何使用 Curl 和 API key 上传到 Google Cloud Storage?

c# - HTTP POST 返回错误 : 417 "Expectation Failed."

bash - 解析nginx访问日志并提取IP,为每个解析的IP检测地理位置

即使 curl 和浏览器给出连贯的文本,Python 请求库也会给出乱码响应