如何通过Android获取服务器中的JSON数据?

时间:2014-08-13 06:43:59

标签: android chat

我正在开发一个新的android应用程序。我有服务器中的所有数据.. 我怎样才能通过android获取JSONData

我很困惑有HttpGet,HttpClient,HttpUrlConnection等。 从哪里获得完整的教程?请帮助我先生..

3 个答案:

答案 0 :(得分:0)

试试这段代码,它在我的项目中运行良好: -

public String connect(){
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = 
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        InputStream is = null;
        //the year data to send
        /*nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1980"));*/

        //http post
        System.out.println("url----------"+url);
        System.out.println("url----------"+get_nameValuePairs);

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(get_nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();

            result=sb.toString();
            //System.out.println("query Result:----------"+result);
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

//      parse json data
        try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);

                //val.add(json_data.getString("password"));

                    //data.append(json_data.getString("first_name")+"\n");
                    //System.out.println(i+"Data found---"+json_data.getString("first_name"));



            }
            //System.out.println(val);

        }catch(JSONException e){
            Log.e("log_tag inside database", "Error parsing data "+e.toString());
        }
        /*Log.d("Inside dataBase", result);*/
        return result;
    }

答案 1 :(得分:0)

private String sendRequestInternal(String url, String body) throws MalformedURLException, IOException {
    Log.i(TAG, "request:\nURL:"+url);
    HttpURLConnection connection=null;
    try{
        connection = (HttpURLConnection)new URL(url).openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("GET");// "POST","PUT" etc.
        if (body != null) { 
            connection.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(body);
            writer.flush();
            writer.close();
        }
        InputStream is = null;
        int code = connection.getResponseCode();
        Log.i(TAG, "code=" + code);
        if ((code / 100) < 4) {
            is = new BufferedInputStream(connection.getInputStream()); // OK
        } else {
            is = new BufferedInputStream(connection.getErrorStream()); // Exception while executing request
        }
        String response = convertStreamToString(is);
        return response;
    } finally {
        if (connection != null) 
            connection.disconnect();
    }
}

private String convertStreamToString(InputStream is) throws IOException {
    InputStreamReader r = new InputStreamReader(is);
    StringWriter sw = new StringWriter();
    char[] buffer = new char[1024];
    try {
        for (int n; (n = r.read(buffer)) != -1;)
            sw.write(buffer, 0, n);
    }
    finally{
        try {
            is.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    return sw.toString();
}

借助方法sendRequestInternal,您可以从服务器获取String。 接下来你应该解析取决于服务器返回给你的JSON。例如,服务器返回下一个JSON数据:

{ 
   "data":"OK",
   "reason":"user",
   "status":200
 }

您可以解析下一步:

public void parseJSON(String json) {
   JSONObject realJson = new JSONObject(json);
   String dataValue = realJson.getString("data");
   int status = realJson.getInt("status");
   Log.d(TAG, dataValue + " " status);
   }

答案 2 :(得分:0)

我建议你使用&#34; Volley&#34;适用于Android的库。它适用于谷歌更快更好的网络库。许多使用凌空的例子:

http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/