嗨,我有以下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/