Json结果返回null

时间:2014-01-08 06:23:42

标签: android json

我是Android.i的新手想要从本地主机获取数据。

String cus_id = etcusid.getText().toString();
new cusdataAsynTask().execute(cus_id);

public class cusdataAsynTask extends AsyncTask<String, Void, Void> {
@Override
        protected Void doInBackground(String... params) {
            String nvpcusid = params[0];
            List<NameValuePair> arg = new ArrayList<NameValuePair>();
            Log.e("nvpcusid: ", "> " + nvpcusid);

            arg.add(new BasicNameValuePair("cus_id", nvpcusid));
ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeServiceCall(URL_CUSTOMERDATA,
                    ServiceHandler.GET,arg);
            Log.e("Response: ", "> " + json);
}
}

在Log中,我得到响应为null;

Service Handler类如下所示

public class ServiceHandler {

    static InputStream is = null;
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            response = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error: " + e.toString());
        }

        return response;

    }

}

我是初学者。请帮助我。

2 个答案:

答案 0 :(得分:0)

试试这段代码:

这是用于从服务器获取jsonObject和jsonArray的类:

public class GetDataJsonFromServer {


    public static JSONObject postJSONfromURL(String url,
            List<NameValuePair> params, int socketFactory, String userAgent)
            throws SSLPeerUnverifiedException {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
        try {
            SchemeRegistry scheme = new SchemeRegistry();
            scheme.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), socketFactory));

            HttpClient httpclient = new DefaultHttpClient();
            HttpProtocolParams.setUserAgent(httpclient.getParams(), userAgent);
            HttpPost httpost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
        }
        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) {
        }

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

    public static JSONArray mygetJSONfromURL(String url,
            List<NameValuePair> params, int socketFactory, String userAgent)
            throws SSLPeerUnverifiedException {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;
        try {
            SchemeRegistry scheme = new SchemeRegistry();
            scheme.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), socketFactory));

            HttpClient httpclient = new DefaultHttpClient();
            HttpProtocolParams.setUserAgent(httpclient.getParams(), userAgent);

            String paramString = URLEncodedUtils.format(params, "utf-8");

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

        } catch (Exception e) {
        }

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

        try {
            jArray = new JSONArray(result);
        } catch (JSONException e) {
        }

        return jArray;
    }

    public static JSONObject getJSONfromURL(String url,
            List<NameValuePair> params, int socketFactory, String userAgent)
            throws SSLPeerUnverifiedException {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
        try {
            SchemeRegistry scheme = new SchemeRegistry();
            scheme.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), socketFactory));

            HttpClient httpclient = new DefaultHttpClient();
            HttpProtocolParams.setUserAgent(httpclient.getParams(), userAgent);

            String paramString = URLEncodedUtils.format(params, "utf-8");

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

        } catch (Exception e) {
        }

        // convert response to string
        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) {
        }

        try {
            jArray = new JSONObject(result);
        } catch (JSONException e) {
        }

        return jArray;
    }

}
你的代码中的

        public class cusdataAsynTask extends AsyncTask<String, Void, jsonObject> {
        @Override
                protected Void doInBackground(String... params) {
                    List<NameValuePair> listParams = new ArrayList<NameValuePair>();
                    JSONObject josn = new JSONObject();
                    String url = params[0];
                    Log.w("url", url);
                    try {
                        josn = GetDataJsonFromServer.postJSONfromURL(url, listParams,
                                80, "Bazan version for Android");
                    } catch (SSLPeerUnverifiedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return josn;
        }

    @Override
    protected void onPostExecute(JSONObject result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (result != null) {
           // add your code here
        }
   }
}

答案 1 :(得分:0)

从服务器获取json数据的代码。它对我来说很好。

private void get_valueFromServer(String php) {
String responseString = null;
try{    
HttpClient httpclient = new DefaultHttpClient();
String url ="your_url"; 
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
// The result is here, in response string
Toast.makeText(getApplicationContext(),responseString,1000).show();
} catch(Exception e) {
}
}