安卓是:http使用参数不工作后 [英] Android: Http post with parameters not working

查看:93
本文介绍了安卓是:http使用参数不工作后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立与参数的HTTP POST请求。我知道有很多的例子在那里,我一直使用的HttpParams,的NameValuePair等尝试,但不能似乎得到服务器的正确的格式。

I need to create an HTTP POST request with parameters. I know there are many examples out there, I have tried using HTTPparams, NameValuePair etc but cant seem to get the correct format for the server.

服务器类型:基于REST的API使用JSON进行数据传输
内容类型:应用程序/ JSON
接受:应用/ JSON
内容长度:47
{用户名:ABCD,密码:1234}

Server Type: REST based API utilizing JSON for data transfer
Content-type: application/json
Accept: application/json
Content-length: 47
{"username":"abcd","password":"1234"}

我可以通过这些信息,但是我似乎无法通过这些PARAMS用户名,密码。这是我的code:

I can pass these headers but I cant seem to pass these params "username","password". Here is my code:

    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);  

我试图调试,但不能看到,如果实体正确或不附......我究竟做错了什么?

I tried to debug, but cant see if entity is attached properly or not... What am I doing wrong?

在此先感谢。 玛斯

推荐答案

试试这个:

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);  

这篇关于安卓是:http使用参数不工作后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆