How to fetch JSONdata in server through Android? [closed]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-14 00:10:26

问题


I am developing a new android application.I have all the data in server.. How I can fetch the JSONData through android??

I am confused there are HttpGet,HttpClient,HttpUrlConnection etc.. Where from I get the full tutorial??please help me sir..


回答1:


I suggest you to use "Volley" library for android .It is for faster and better networking library by Google . Many examples of using volley :

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




回答2:


Try this code, Its working fine in my project:-

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



回答3:


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();
}

With the help of the method sendRequestInternal you can get a String from the server. Next you should parse depends on JSON that the server returns to you. For example server returns next JSON data:

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

You can parse this next:

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


来源:https://stackoverflow.com/questions/25279661/how-to-fetch-jsondata-in-server-through-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!