我需要创建一个包含参数的HTTP POST请求.我知道有很多例子,我尝试使用HTTPparams,NameValuePair等,但似乎无法获得正确的服务器格式.
服务器类型:基于REST的API,使用JSON进行数据传输
Content-type:application / json
接受:application / json
内容长度:47
{ “用户名”: “ABCD”,“密码”: “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"); 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);