Android POST Json数据

时间:2011-12-08 00:54:39

标签: android wcf json

经过大量搜索和反复试验后,我发现了我认为以正确的方式将表单数据以json格式发布到Rest服务(在本例中为WCF服务)。

我的问题是,尽管json格式正确,但当我将它添加到.SetEntity时,我的json字符串变成了一个数字数组,它抛出一个org.apache.http.client.HttpResponse.Exception

我正在使用Localtone的POST JSON from Android using HttpClient略有改动的版本,它处于测试模式,并且全部:

public String makeRequest() throws Exception {

        //set up the params here

        Map<Object,String> mp2=new HashMap<Object, String>();
        mp2.put("uName", "myUName");
        mp2.put("uPass", "myUPass");

        Map<String, Object> params=new HashMap<String, Object>();
        params.put("MyDC", mp2);  

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpost = new HttpPost(getString(R.string.CONST_RestService) + "/json/Login");
        Iterator<Entry<String, Object>> iter = params.entrySet().iterator();

        JSONObject holder = new JSONObject();

        while(iter.hasNext()) {
        Map.Entry pairs = (Map.Entry)iter.next();
        String key = (String)pairs.getKey();
        Map<?, ?> m = (Map)pairs.getValue();

        JSONObject data = new JSONObject();
        Iterator iter2 = m.entrySet().iterator();
        while(iter2.hasNext()) {
        Map.Entry pairs2 = (Map.Entry)iter2.next();
        data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }
        holder.put(key, data);
        }

        StringEntity se = new StringEntity(holder.toString());
        httpost.setEntity(se);
        httpost.setHeader("Accept", "application/json");
        httpost.setHeader("Content-type", "application/json");

        ResponseHandler responseHandler = new BasicResponseHandler();
        response = httpclient.execute(httpost, responseHandler);

        return response.toString();
        }

这一切都很有效:

StringEntity se = new StringEntity(holder.toString());

holder.toString()被正确填充为

{"MyDC":{"uName":"myUName","uPass":"myUPass"}}

但是一旦se填充,se内容就变成:

[123, 34, 77, 121, 68, 67, 34, 58, 123, 34, 117, 78, 97, 109, 101, 34, 58, 34, 109, 121, 85, 78, 97, 109, 101, 34, 44, 34, 117, 80, 97, 115, 115, 34, 58, 34, 109, 121, 85, 80, 97, 115, 115, 34, 125, 125]

然后将其作为httpost.entity发送,然后杀死所有内容。

那么,这里发生了什么?为什么json字符串变成数字数组?

任何洞察力?

由于

戴夫

1 个答案:

答案 0 :(得分:0)

se.getContent()将返回ByteArrayInputString。您需要读取缓冲区并将流转换为字符串