【问题标题】:Change NameValuePair separator from '=' to ':'将 NameValuePair 分隔符从 '=' 更改为 ':'
【发布时间】:2013-09-21 19:17:54
【问题描述】:

我正在尝试发送HttpPost 请求,据我了解,您可以这样做:

            HttpClient httpClient = new DefaultHttpClient(); 
            HttpPost post = new HttpPost(uri[0]); 
            try {
                List<NameValuePair> nvp = new ArrayList<NameValuePair>(); 
                nvp.add(new BasicNameValuePair("{\"UserName\"", "\"michigan\""));
                nvp.add(new BasicNameValuePair("\"Password\"", "\"fanaddicts\""));
                nvp.add(new BasicNameValuePair("\"DeviceHarwareId\"", "\"NW58xfxz/w+jCiI3E592degUCL4=\""));
                nvp.add(new BasicNameValuePair("\"DeviceTypeId\"", "\"1\"}"));
                post.setEntity(new UrlEncodedFormEntity(nvp));

                response = httpClient.execute(post); 

                Log.i("Feed Response", "Feed: " + response.getStatusLine().getStatusCode()); 

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

我遇到的问题是实体看起来像这样:

[{"UserName"="michigan", "Password"="fanaddicts", "DeviceHarwareId"="NW58xfxz/w+jCiI3E592degUCL4=", "DeviceTypeId"="1}]

但是由于服务器的设置方式,我需要它看起来像这样:

[{"UserName":"michigan", "Password":"fanaddicts", "DeviceHarwareId":"NW58xfxz/w+jCiI3E592degUCL4=", "DeviceTypeId":"1}]

您会注意到,不是等号 (=) 符号,而是冒号 (:) 分隔键/值对。

我的问题是:我该如何解决这个问题?

【问题讨论】:

  • 考虑使用 JSONObject 而不是 UrlEncodedFormEntity -- 因为看起来您想要的是 JSON 字符串,而不是 URL 编码的字符串。
  • @jedwards:你为什么不把这个写成答案?
  • @jedwards 将您的评论作为答案,我会接受。有效。好想法。谢谢。
  • @Blaine:太好了,很高兴能提供帮助

标签: java android httprequest


【解决方案1】:

您可能会考虑使用JSONObject 而不是 UrlEncodedFormEntity -- 因为看起来您想要的是 JSON 字符串,而不是 URL 编码的字符串。

【讨论】:

    【解决方案2】:

    更好的方法是将 json 字符串序列化成字典。字典索引可以访问的json结构数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多