androidrestful-authenticationandroid-json

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.


Solution

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