1

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

My class is mentioned below.

@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;
}

I parsed the checkxml string from another method.

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.

4
  • 1
    Post logcat. Also, highlight the lines that cause the exception. Commented Jul 15, 2014 at 11:18
  • 1
    do you want to send the json to server ? Commented Jul 15, 2014 at 11:19
  • 1
    if you parse string to json you can use : code.google.com/p/google-gson Commented Jul 15, 2014 at 11:21
  • Refer to this. You are getting the exception because your HTTP GET params are too long. Yes, HTTP GET, because that's how you supply the params. Also, this is a duplicate of given link. Commented Jul 15, 2014 at 11:26

2 Answers 2

1

call it like 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 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"
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a method I wrote that might help you,

public JSONObject connectClient(){
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 20000);
    httpClient= new DefaultHttpClient(params);

    HttpResponse httpResponse;
    InputStream inputStream=null;
    try{
        HttpPost httpPost=new HttpPost(__PUT_YOUR_URL_HERE__);
        StringEntity se=new StringEntity(__PUT_YOUR_STRING_HERE__);
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(se);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept", "application/json");

        httpResponse = httpClient.execute(httpPost);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        long responsesize = httpResponse.getEntity().getContentLength();
        HttpEntity entity=httpResponse.getEntity();
        try{
            inputStream=entity.getContent();
        }
        catch(IllegalStateException ise){
            ise.printStackTrace();
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
        BufferedReader reader = null;
        try {
             reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s=sb.toString();

        if(responseCode==200)
            output= new JSONObject(s);
        else{
            output.put("STATUS", "FAIL");
            output.put("ERRORCODE", responseCode);
            output.put("DATA_SIZE", responsesize);
            output.put("DATA_CONTENT", s);
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }

    return output;
}

Response is again given back is a JSONObject, you can edit that out if you want.

2 Comments

how to put name for the Parameter String which is parse as a parameter?
@user2512822 I didn't understand your comment? You would do something like String s="{"layoutid": 1,"total": "2.95", .......[ the whole of your json string ]......}". Then StringEntity se=new StringEntity(s); Of course if you actually are hardcoding your string into your code like that then you will have to escape all the " with \.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.