在android中调用json webservice

时间:2014-07-17 09:37:09

标签: java android json web-services

我是Android新手,我需要一点帮助,我试图调用json webservice但我总是得到空指针异常。下面是我的代码

方法名称: AuthorizeAndLoginWithVinlite

public String readJSON(String strURL) throws Exception {

    strURL = "https://www.vinlite.com/DesktopModules/Vinlite/API/MobileService/";

    HttpClient httpClient = new DefaultHttpClient();
    String Content;
    String Error = null;
    URI url = new URI(strURL);
    HttpPost httpost = new HttpPost(url);
    //Content = sb.toString();
    StringBuilder stringBuilder = new StringBuilder();


    Map<String, Object> params = new HashMap<String, Object>();
    params.put(new String("VINLITEAPPID"), "Vin1.0"); 
    params.put(new String("VINLITEAPPSECRET"), "AppTest-Vin"); 
    params.put(new String("portalID"), "0"); 
    params.put(new String("DEVICETOKEN"), "ECF3392D-30D7-466B-9BBB-AD"); 
    params.put(new String("DEVICEPLATFORM"), "IOS"); 
    params.put(new String("VinliteUsername"), "test@yahoo.com"); 
    params.put(new String("VinlitePassword"), "test"); 

    JSONObject holder = getJsonObjectFromMap(params);

  //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);

    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/x-www-form-urlencoded");
    try {

        HttpResponse response = httpClient.execute(httpost);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();
        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }        
    return stringBuilder.toString();
}

    private static JSONObject getJsonObjectFromMap(Map<String, Object> params) throws JSONException {
//all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //STORES JSON
    JSONObject holder = new JSONObject();


    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();
        String value = (String)pairs.getValue();
        //params.put(new String("VINLITEAPPID"), "VinSell1.0"); 
        //Create a new map
        Map<String, Object> m = new HashMap<String, Object>();

        m.put(key, value);

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        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);
    }
    return holder;
}

}

1 个答案:

答案 0 :(得分:0)

private class GetData extends AsyncTask<String, Void, JSONObject>{

        @Override
        protected JSONObject doInBackground(String... params) {
            InputStream is = null;
            String result = "";
            JSONObject jsonObject = null;

            try {           
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(params[0]); //PARAMS[0] will contain URL
                HttpResponse response = httpclient.execute(httpGet);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } catch(Exception e) {
                return null;
            }

            try {           
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();             
            } catch(Exception e) {
                return null;
            }

            try {
                jsonObject = new JSONObject(result);            
            } catch(JSONException e) {
                return null;
            }

            return jsonObject;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //DO THINGS LIKE SHOWING PROGRESS DIALOG ETC
        }

        @Override
        protected void onPostExecute(JSONObject response) {
            super.onPostExecute(response);
            ??YOU"VE YOUR JSON HERE DO WHAT EVER YOU WANT
        }
    }

您可以像上面这样打电话给

new GetData().execute(URLTOGETDATA);