Monday, July 18, 2016

Calling JIRA REST Web service (Basic Authentication) in android and getting response in JSON.


1- MainActivity

package restapi.siddhu.test.com.restapi;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.os.AsyncTask;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

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

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.Base64;


public class MainActivity extends AppCompatActivity {

    String text = "siddhu";
    Button b;
    private static String BASE_URL = "https://yourjiraaddress.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        b = (Button)findViewById(R.id.my_button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                b.setClickable(false);
                //Create instance for AsyncCallWSGetProjectInfo
                AsyncCallWSGetRetrospect objAsyncCallWSGetRetrospect = new AsyncCallWSGetRetrospect();
                //Call execute
                objAsyncCallWSGetRetrospect.execute();
                // Inflate the layout for this fragment
            }
        });
    }


    private class AsyncCallWSGetRetrospect extends AsyncTask {

        @Override
        protected Void doInBackground(String... params) {
            String auth = new String(Base64.encode("userid:password"));
            try {
            String projects = invokeGetMethod(auth, BASE_URL+"/rest/api/2/project");
            System.out.println(projects);

            JSONArray projectArray = new JSONArray(projects);
            for (int i = 0; i < projectArray.length(); i++) {
                JSONObject proj = projectArray.getJSONObject(i);
                System.out.println("Key:"+proj.getString("key")+", Name:"+proj.getString("name"));
                text = text + "Key:"+proj.getString("key")+", Name:"+proj.getString("name");
            }
            } catch (Exception e) {
                System.out.println("Username or Password wrong!");
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            if (text!=null) {
                EditText et = (EditText)findViewById(R.id.my_edit);
                et.setText(text);
            }
            Button b = (Button)findViewById(R.id.my_button);
            b.setClickable(true);
        }

        @Override
        protected void onPreExecute() {
            //Toast.makeText(getContext(), "Fetching Retrospect information of Sprint ...", Toast.LENGTH_SHORT).show();
            //loading.show();
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }
    }

    private static String invokeGetMethod(String auth, String url) throws Exception, ClientHandlerException {
        Client client = Client.create();
        WebResource webResource = client.resource(url);
        ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
                .accept("application/json").get(ClientResponse.class);
        int statusCode = response.getStatus();
        if (statusCode == 401) {
            throw new Exception("Invalid Username or Password");
        }
        return response.getEntity(String.class);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


2- content_main.xml

    TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Http GET Demo"
    Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="GET"
        android:id="@+id/my_button"
        android:layout_below="@+id/my_edit"
        android:layout_alignLeft="@+id/my_edit"
        android:layout_alignStart="@+id/my_edit"
        android:layout_marginTop="62dp" 
    EditText
        android:layout_margin="20dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minLines="15"
        android:maxLines="15"
        android:textSize="12sp"
        android:editable="false"
        android:id="@+id/my_edit"


3- AndrodManifest.xml


   uses-permission android:name="android.permission.INTERNET"



Note: Please add following jar in android studio/project
jersey-client-1.8.jar
jersey-core-1.8.jar
json-20090211.jar
rest-client-1.0.jar



No comments: