1

I created a web service in asp.net which is to receive the following url:

http://localhost:31804/api/defaultapi/login?empNum=123456&surname=Yusuf 

and send the following json {"$id":"1","EmployeeID":2,"Firstname":"Abayomi","Surname":"Yusuf","DepartmentID":1,"EmployeeNumber":"123456"}

This works on my browser.

Now I am trying to consume that web service in my android app. I'm a total beginner and i am using the JSON parser class created by Andrew Barber here How to parse JSON in Android (last comment)

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

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();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

this is how i used it in my code. A button has loadHome method as its onClick event

public class Main extends Activity {

private SharedPreferences employeeDetails;

private static final String EMP_ID = "EmployeeID";
private static final String EMP_NAME = "Firstname";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
}

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

public void loadHome(View view)
{
    EditText empNumEditText = (EditText)findViewById(R.id.employeeNumEditText);
    EditText surnameEditText = (EditText)findViewById(R.id.surnameEditText);
    TextView empNumError = (TextView)findViewById(R.id.empNumWarningTextView);
    TextView surnameError = (TextView)findViewById(R.id.surnameWarningTextView);
    TextView displayError = (TextView)findViewById(R.id.errorTextView);

    String employeeNumber = empNumEditText.getText().toString();
    String surname = surnameEditText.getText().toString();

    //ensure that the form was completed
    if((employeeNumber.length()>0) && (surname.length()>0))
    {
        try{
            String encodedEmployeeNumber = URLEncoder.encode(employeeNumber, "UTF-8");
            String encodedSurname = URLEncoder.encode(surname, "UTF-8");

            String loginURL = "localhost:31804/api/defaultapi/login?empNum=" + encodedEmployeeNumber + "&surname=" + encodedSurname;


            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(loginURL);
            String empId = json.getString(EMP_ID);
            String empSur = json.getString(EMP_NAME);

            displayError.setText(empSur);
            }
        catch(Exception e){
            displayError.setText("Whoops - something went wrong!");
            e.printStackTrace();
        }

    } 
    else //display error messages
    {
        if (employeeNumber.length()>0){
            empNumError.setText(" ");
        }else{
            empNumError.setText("Enter Your Employee Number");
        }

        if (surname.length()>0){
            surnameError.setText(" ");
        }else{
            surnameError.setText("Enter Your Surname");
        }
    }

}

I keep getting the error ("Whoops - something went wrong!") in the displayError textView. What am i doing wrong.

Here is a link to the stack trace http://3.bp.blogspot.com/-jJnZ71KC5ZM/UUjVQhbzKCI/AAAAAAAAAMk/v9j_bhIkOEg/s1600/1.jpg

Community
  • 1
  • 1
ylinkz
  • 181
  • 1
  • 2
  • 13
  • 2
    Post the stack trace for the exception. – Gabe Sechan Mar 19 '13 at 20:38
  • @GabeSechan I have included the stack trace – ylinkz Mar 19 '13 at 21:17
  • @ylinkz : Your url starts `localhost` which makes me think you are running this on an emulator on the same machine as the asp.net service - correct? If that's the case, then don't use `localhost`, you need to use the numeric IP address 10.0.2.2. See the documentation for Emulator Networking http://developer.android.com/tools/devices/emulator.html#emulatornetworking – Squonk Mar 19 '13 at 22:09
  • @Squonk, i have discovered that i cannot even browse my local web application on the emulator's browser. I have tried 10.0.2.2, i even used the IPv4 address as suggested by Dave in the comment below, still no luck. I gues that has to work before i can even call the local web service, right? – ylinkz Mar 20 '13 at 11:06
  • @ylinkz : The address 10.0.2.2 is correct for accessing your development machine's loopback interface. Don't use the IPv4 address as Dave advised. Try again with 10.0.2.2 then post the stack trace. – Squonk Mar 20 '13 at 22:40

3 Answers3

0

Unless I'm missing something, your problem may be in your URL. You're specifying

String loginURL = "localhost:31804/api/defaultapi/login?empNum=" + encodedEmployeeNumber + "&surname=" + encodedSurname;

The host name "localhost" should always resolve to 127.0.0.1. Any 127.x.x.x address should point to your local stack...so if you're running on your phone, this would be your phone. Depending on your configuration, it could be your AVD when running in the AVD. Try changing it to the routable port and see if that makes a difference.

If you're on windows, go to a command prompt and use:

ipconfig

Look for your LAN adapter and use the IPv4 Address instead of "localhost".

Dave
  • 300
  • 1
  • 7
  • I can't add comments, but, in answer to one of your other questions. Yes, you will need to get it working in a browser first -- at least to test it. My suggestion is to just make a very simple page that returns some text. Make sure you can browse to that (that will take out everything but the browser out of the loop). If you can get to that, run your app against that URL and see if the app gets the results. If it does, you know you're communicating with the server ok. Then get your API to work right. – Dave Mar 20 '13 at 17:50
0

I have created a library that i have used along with all the developers i work with for the past year. Feel free to clone it from github. Try it and see if it helps you with doing rest requests.

https://github.com/darko1002001/android-rest-client

It helps you handle the Async execution of requests and executes them in a separate service with a tread pool to manage the concurrent connections.

DArkO
  • 15,880
  • 12
  • 60
  • 88
0
String response = performRequestAsString(MY_URL, "GET");
Log.v("REsponse from web server",response);

// put this below

public static String performRequestAsString(String url, String method) 
{
    String value = null;

    try {

        if (method == "POST") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.e("Request_Url", "" + url);
            HttpPost httpPost = new HttpPost(url);              
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);

        } else if (method == "GET") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            Log.e("Request_Url", "" + url);
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            value = convertStreamToString(is);
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return value;
}

// for Access WebAPI

new GetData().execute();


private class GetData extends AsyncTask<String, String, String> {
        private ProgressDialog progressDialog;
        private String response = "";
        private JSONArray jRootArray;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setMessage("Loading ...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(false);
            progressDialog.show();

        }

        @Override
        protected String doInBackground(String... args) {

            response = WebAPIRequest.performRequestAsString(MY_URL, "GET");


            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (response == null) {

                        Toast.makeText(mContext, "Please Try Again",
                                Toast.LENGTH_SHORT).show();
                    } else {

                    }

                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(String args) {
            progressDialog.dismiss();

        }
    }
Hiren Patel
  • 52,124
  • 21
  • 173
  • 151