java - 如何在android中使用HTTP post方法解析JSON数据?

标签 java android json http httprequest

我想将 JSON 数据解析为 Web 服务的字符串参数。

下面提到了我的类(class)。

@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 字符串。

checkxml 由以下字符串形式的详细信息组成。

   {
    "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
        }
    ]
}

它抛出了一个非法参数线程池异常。请让我知道如何将此数据解析为上述 url 的参数。

最佳答案

new GetData().execute(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就是这个

{
    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"
    }
}

关于java - 如何在android中使用HTTP post方法解析JSON数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24756748/

相关文章:

java - 无法引用以不同方法定义的内部类中的非最终变量-请帮助我,我是新手

javascript - 如何将 react-native 与 php 一起使用,获取返回数据始终为 null

java - 在 Java 中创建 XML 日志文件

java - 字符串是否包含三个逗号分隔的数字?

java - 从 adt 使用 eclipse 后,在 mac 上创建纯 java 项目时出错

ruby-on-rails - 使用 Postman 和 Rails 时出现意外的 '<' 错误

python - 在 Python 中将 SQL 转换为 json

java - 使用法拉利方法求四次方程的实根

java - 在xml和java代码中创建对象的区别

android - Google Play 游戏和个人资料图片