简体   繁体   中英

how to connect android to restful api


I'm making an app which let people login, sign in, sign up, write something and save it to database.
So I decided to chose Restful Api with Slim Framework. I publish it in my host and test by extension of google chrome call Advanced Rest Client. Everything like login ,signin, sign up, wite something, update it, delete it.. work fine.

For example: I log in with information:
email: stark@gmail.com
password: abc
then the result is something like that.

{
error: false
name: "Kien"
email: "nguyenkien1402@yahoo.com"
apiKey: "fc2aee103c861026cb53fd8920b10adc"  
createdAt: "2015-06-24 00:28:01"
}


But when I used it in my android app. I cannot connect and get information by JSON. Please tell my how to solve this problem.
Thank you. Sorry about my english, it's not native english.

To connect to the restful API, the following steps you have to do

  • give internet access
  • have to do http connection
  • have to to take stream input

Give Internet Access to give internet access to the app we have to add this piece of code in the file " AndroidManifest.xml"

<uses-permission android:name="android.permission.INTERNET"/>

To do the second and third step we have to create a new java class as when we are connecting to the restful API, it will run in the background and MainActivity does not allow the background task.

Let say we create a new java class "fetchData" to get data from the API. to do the remaining task we have to use this piece of code

URL url = new URL(API ADDRESS);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

now you get the JSON file using the "Bufferedreader.readLine()"

then the class file looks like this

import android.os.AsyncTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class fetchData extends AsyncTask<Void,Void,Void> {
    String data ="";
    String dataParsed = "";
    String singleParsed ="";
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("https://api.myjson.com/bins/k3p10");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }


            JSONArray JA = new JSONArray(data);
            for(int i =0 ;i <JA.length(); i++){
                JSONObject JO = (JSONObject) JA.get(i);
                singleParsed =  "Name:" + JO.get("name") + "\n"+
                        "email:" + JO.get("email") + "\n"+
                        "Error:" + JO.get("error") +  "\n";

                dataParsed = dataParsed + singleParsed +"\n" ;


            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

    }
}

from the JSON array, you can extract everything from the JSON you get from the API. then you can use the information as per your requirement.

If your url is generating json response, then you have to read that.

public static String  sendGet(String url) throws Exception {



        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");



        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();


        return response.toString(); //here is your response which is in string type, but remember that the format is json. 

    }

Then convert your response to json:

JsonObject obj = new JsonObject(response);

I solved it. It up to my class about CRUD JSON. Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM