【问题标题】:Create a json string with List<NameValuePair> in android在 android 中使用 List<NameValuePair> 创建一个 json 字符串
【发布时间】:2014-01-31 14:26:08
【问题描述】:

我想用 Android 向一个 url 发送一个 http 请求。 我是一名 iOS 开发人员,现在正在尝试学习 Android。 我曾经在 iOS 中发送JSON 字符串,如下所示

 {"function":"login", "parameters": {"username": "nithin""password": "123456"}}

如何在 Android 中发送此内容? 我试过List&lt;NameValuePair&gt;,但找不到合适的解决方案。

我尝试过的完整代码 -

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("function", "login"));
        nameValuePairs.add(new BasicNameValuePair("username", "nithin"));
        nameValuePairs.add(new BasicNameValuePair("password", "123456"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

【问题讨论】:

    标签: java android json http


    【解决方案1】:

    我认为 JsonStringer 在这里对您来说既简单又有用..

    试试这个:

       HttpPost request = new HttpPost(URL);
       request.setHeader("Accept", "application/json");
       request.setHeader("Content-type", "application/json");
       JSONStringer vm;
       try {
             vm = new JSONStringer().object().key("function")
            .value(login).key("parameters").object()
            .key("username")
            .value(nithin).key("password").value("123456")
            .endObject().endObject();
      StringEntity entity = new StringEntity(vm.toString());
      request.setEntity(entity);
      HttpClient httpClient = new DefaultHttpClient();
      HttpResponse response = httpClient.execute(request);
    

    【讨论】:

    • 简单地说:Bufferedreader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));然后像往常一样 while 循环和 readline...
    • 谢谢人..我得到的字符串是 {"main":{"status":"true","id":"3","username":"Christian Martin","password ":"123456","email":"nithin@newagesmb.com","message":"您已成功登录","image":"http:\/\/www.menchd.com\/assets\ /upload\/users\/1386921988.jpg","terms_status":"Y","chat_status":"Y","profile_count":4568},"questions":{"total_questions":40,"answerd_questions": 40}} 从这里如何获取键的值 - 用于“状态”
    • 没有。使用EntityUtils.toString。使用 BufferedReader 和 readLine 没有任何意义。没有迹象表明结果中有偶数行。而readLine一个一个地读取每个字符,非常的慢。
    • @njzk2 感谢您的有用建议。
    • EntityUtils 也已弃用,现在我应该使用哪个...?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多