用Java中的数据发送HTTP POST请求
问题描述:
我正在尝试执行一个简单的http post请求,其中包含数据,但是我发送数据的网址正在向我返回错误信息,表明查询必须包含'code'参数。用Java中的数据发送HTTP POST请求
我们在Python中有一个脚本可以工作。它只是做到这一点:
import requests
build_data = {'code': '827h46fh38fjg623hd6che6fhw63hf6239k589'}
build_data['workflow.reponame'] = 'test'
result = requests.post('https://SomeUrl', data=build_data, verify=False)
我的Java代码:
public void postReceive()
{
String payload = "{'code': '827h46fh38fjg623hd6che6fhw63hf6239k589','workflow.reponame': 'test'}"
makeRequest(payload)
}
private void makeRequest(String payload)
{
try
{
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
String url = "https://SomeUrl";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json; charset=utf8");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(payload.getBytes("UTF-8"));
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
/*HttpClient client = MySSLSocketFactory.getNewHttpClient();
HttpPost post = new HttpPost("https://SomeUrl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", payload));
//nameValuePairs.add(new BasicNameValuePair("verify", false));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);*/
}
catch(Exception e)
{
}
}
我评论使用HttpClient的代码,但它做同样的事情。难道我做错了什么?
答
{'code': '827h46fh38fjg623hd6che6fhw63hf6239k589'}
是一个python构造,它不是“按原样”发送,而是由post
方法(解包和表单编码)使用。而不是
:
nameValuePairs.add(new BasicNameValuePair("data", "{'code': '827h46fh38fjg623hd6che6fhw63hf6239k589'}"));
,你应该这样做:
nameValuePairs.add(new BasicNameValuePair("code", "827h46fh38fjg623hd6che6fhw63hf6239k589"));
我不知道你如何检查服务器端的参数,但在你的有效载荷那些额外的“字符真的有必要? “{code:827h46fh38fjg623hd6che6fhw63hf6239k589,workflow.reponame:test}” – user 2014-10-01 13:54:25