我需要创建一个带有参数的 HTTP POST 请求。我知道有很多例子,我尝试过使用 HTTPparams、NameValuePair 等,但似乎无法获得服务器的正确格式。
Server Type: REST based API utilizing JSON for data transfer
Content-type: application/json
Accept: application/json
Content-length: 47
{"username":"abcd","password":"1234"}
我可以传递这些标头,但我似乎无法传递这些参数“用户名”、“密码”。这是我的代码:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
我尝试调试,但无法查看实体是否正确附加...我做错了什么?
提前致谢。
马兹
尝试这个:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)