我有一个CURL命令,当我执行它时工作正常。下面是curl命令。如果我正在尝试使用HTTP客户端在java中编写相同的curl命令,我将获得HTTP 403.我无法理解为什么在执行CURL时我没有得到同样的错误,但在代码中我得到了。有人可以帮我修理我的代码。
curl -v -X POST "http://iapi-va3.svcmot.com/v1/gui/user.json?appid=4KCPMNRRT4VJBY54V3888YUOLHLICK28" -d '{"providerType":"MOTOID","email":"1234@idmtest.com","password":""}'
以下是我的Java代码。
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://iapi-va3.svcmot.com/v1/gui/user.json?appid=4KCPMNRRT4VJBY54V3888YUOLHLICK28");
post.addHeader("User-Agent","curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2");
post.addHeader("Host","iapi-va3.svcmot.com");
post.addHeader("Accept","curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2");
post.addHeader("Accept", "*/*");
post.addHeader("Content-Length", "66");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
Header[] headerArray=post.getAllHeaders();
for(Header h:headerArray)
{
System.out.println(h.getName()+"---"+h.getValue());
}
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("providerType", "MOTOID"));
nameValuePairs.add(new BasicNameValuePair("email", "1234@idmtest.com"));
nameValuePairs.add(new BasicNameValuePair("password", ""));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
System.out.println("\n"+response);
//System.out.println(response.getStatusLine());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println("\n"+line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
不同之处在于,您是从curl向服务器发送json,但在程序中将其作为参数发送。
显然,在发送之前,您需要在应用程序中将params序列化为json。