在post方法android中处理json响应

时间:2015-02-05 16:50:04

标签: android json eclipse api facebook-rest-api

我是android的新手。我有一个休息API post方法。我必须为API提供电子邮件和密码。它将以json格式提供响应,如下面的格式

{
error: "This email is already registered "
status: 404
}

原始回复将采用以下形式

{"error":"This email is already registered\n","status":404}

我成功发送了名称值对,但我不知道如何处理这种类型的响应。任何人都可以帮我解决这个问题吗?这是我的代码

protected String doInBackground(String... params) {

            //HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("https://zigron.goabode.com/api/registration/new");
        PostMethod post = new PostMethod("https://zigron.goabode.com/api/registration/new");

        String resp=null;

        try 
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("email", email_s ) );
            nameValuePairs.add(new BasicNameValuePair("password", pwd_s ) );

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            System.out.println(nameValuePairs);

            resp=post.getResponseBodyAsString();
            return resp;

        }

最后两个陈述不正确。我将其作为一个不应该完成的字符串处理

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码访问Post Webservice ...

public static List<NameValuePair> addMediaParameter() {
    List<NameValuePair> params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("offset", "0"));
    params.add(new BasicNameValuePair("length", "100"));
    // params.add(new BasicNameValuePair("limit", "3"));
    return params;
}

public static String responseRetriever(String url,
        List<NameValuePair> values) {
    try {
        String paramString = "";
        if (values != null)
            paramString = URLEncodedUtils.format(values, "utf-8");

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url + paramString);
        HttpResponse response;
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String data = EntityUtils.toString(entity);

            if (data != null && data.length() > 0)                  
                return data;
            else
                return null;
        }
    } catch (Exception e) {
        Log.e("responseRetriever", e.toString());
    }

    return null;
}



String response_data = responseRetriever("yourURL", addMediaParameter());

此response_data将为您提供Web服务的完整响应,如String。现在您可以根据您的响应解析String:Like

 JSONObject jsonresponse = new JSONObject(response_data);
String error_message = jsonresponse.getString("error");

根据您的回复进行解析。

答案 1 :(得分:0)

我正在使用https链接,因为我需要编写一个TrustManager。默认情况下,Android不会接受https,而不会像http那样接受。