如何在Android的HTTP POST方法解析JSON数据? [英] how to parse JSON data with the HTTP post method in android?

查看:315
本文介绍了如何在Android的HTTP POST方法解析JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解析JSON数据作为一个字符串参数传递给Web服务。

I want to parse JSON data as a string parameter to the web service.

我的类如下所述。

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();
    //URL url = new URL("http://192.168.1.44:8080/api/BeVoPOSAPI/checklogin?nodeid=2");
    //Log.d("shankar: ", ip+":"+port+"/"+node);
    //String url = "http://"+ip+":"+port+"/api/BeVoPOSAPI/checklogin?nodeid="+node+"&login=";
    //String url = "http://"+ip+":"+port+"/api/BeVoPOSAPI/checklogin?nodeid="+node+"&login=";
    //String url = "http://192.168.1.60:8081/api/BeVoPOSAPI/checklogin?nodeid=2&login=";
    String url = "http://ipa.azurewebsites.net/pos/savecheck?nodeid=2&checkxml=";
    try {
        // Add your data
        String checkxml = new String(params[0]);
        ;
        url = url.concat(checkxml);
        Log.d("password", checkxml);
        //HttpPost httppost = new HttpPost(url);

        //HttpParams httpParameters = new BasicHttpParams();
        //HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
        //HttpConnectionParams.setSoTimeout(httpParameters, 1000);

        //HttpClient httpClient = new DefaultHttpClient(httpParameters);
        //HttpContext localContext = new BasicHttpContext();

        HttpPost httpget = new HttpPost(url);
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        int timeoutConnection = 300;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 500;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                /*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                Log.d("password", password_check);
                nameValuePairs.add(new BasicNameValuePair("login", password_check));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
        // Execute HTTP Post Request
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpclient.execute(httpget);
        Log.d("Status", response.toString());
        int responseCode = response.getStatusLine().getStatusCode();
        String str = Integer.toString(responseCode);
        Log.d("Responce code", str);
        switch (responseCode) {
            case 200:
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    Log.d("Responce", responseBody.toString());
                    String jsonString = responseBody.toString();

                }
                break;
        }
    } catch (SocketTimeoutException e) {
        error = "SocketTimeoutException";
    } catch (ConnectTimeoutException e) {
        error = "connectionTimeoutException";
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        //Log.d("Error", e.toString());
        error = "ClientProtocolException";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //Log.d("Error", e.toString());
        error = "IOException";
    }
    return null;
}

我解析从另一个方法checkxml字符串。

I parsed the checkxml string from another method.

该checkxml由下面的详细信息为字符串。

The checkxml consists of the details below as a string.

   {
    "layoutid": 1,
    "total": "2.95",
    "checkdiscountpercentage": 0,
    "gratuityid": "",
    "status": 141,
    "checkdiscountshiftlevelid": "",
    "checktimeeventid": "",
    "isprintonbill": "",
    "userid": 1,
    "gratuitypercentage": "",
    "checkdiscountreason": "",
    "ordertype": 210,
    "noofcustomer": 1,
    "generatedon": "",
    "istaxexcemt": 0,
    "checkdefinitiontype": "",
    "tableid": 1,
    "customerid": 0,
    "ticket": "new",
    "checkdiscountamount": "0",
    "tablename": 100,
    "checkdiscountistaxadjust": "1",
    "checkdiscounttax": "0",
    "products": [
        {
            "menuitemname": "2",
            "menuitemid": 1,
            "reason": "",
            "discountpercentage": 0,
            "seatid": 1,
            "timeeventid": "",
            "SaleDetailsMenuItem_ID": "2",
            "istaxexcemt": "2",
            "taxamount": "0.2100",
            "discounttax": "0",
            "definitiontype": "",
            "modifiers": [
                {}
            ],
            "discountamount": "0",
            "istaxinclude": "2",
            "seatname": "",
            "shiftlevelid": "2",
            "discountshiftlevelid": "",
            "discountreason": "",
            "status": "2",
            "coursingid": "",
            "qty": 2,
            "ordertype": "",
            "taxpercent": "2",
            "taxids": [
                {
                    "taxpercent": "7",
                    "Amount": "0.21",
                    "taxid": "1"
                }
            ],
            "holdtime": 0,
            "price": 2.95,
            "discountistaxadjust": 1,
            "price2": 3
        }
    ]
}

抛出了非法参数线程池例外。请让我知道如何解析这个数据作为参数传递给上面的网址。

It threw an illegal argument and thread pool exception. Please let me know how to parse this data as a parameter to the above url.

推荐答案

叫它像新的GetData()执行(URL);

private class GetData extends AsyncTask<String, Void, JSONObject> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = ProgressDialog.show(Calendar.this, "", "");
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        String response;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            HttpResponse responce = httpclient.execute(httppost);
            HttpEntity httpEntity = responce.getEntity();

            response = EntityUtils.toString(httpEntity);
            Log.d("response is", response);

            return new JSONObject(response);

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(JSONObject result) 
    {
        super.onPostExecute(result);

        progressDialog.dismiss();

        if(result != null)
        {
            try
            {
                JSONObject jobj = result.getJSONObject("result");

                String status = jobj.getString("status");

                if(status.equals("true"))
                {
                    JSONArray array = jobj.getJSONArray("data");

                    for(int x = 0; x < array.length(); x++)
                    {
                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put("name", array.getJSONObject(x).getString("name"));

                        map.put("date", array.getJSONObject(x).getString("date"));

                        map.put("description", array.getJSONObject(x).getString("description"));

                        list.add(map);
                    }

                    CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);

                    list_of_calendar.setAdapter(adapter);
                }
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
        else
        {
            Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
        }
    }
}

// JSON是这个

// Json is this

{
    result: {
        data: [
            {
            name: "KICK-OFF personal . 6-7 augusti",
            date: "2014/08/06 ",
            description: "6-7 augusti har pedagogerna grov planering inför höst terminen projekt. Skaparverkstan har öppet som vanligt med vikarier."
            }
        ],
        status: "true",
        description: "Data found"
    }
}

这篇关于如何在Android的HTTP POST方法解析JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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