1

I'm new to Android and Web Services programming using Java and I've been having issues connecting my android app to my java web service. I've deployed the web service on tomcat and it's connecting on my phone browser but the HttpClient returns null each time I try connecting from my Android app.

Here is my source code.

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

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

    return response;

}

}

private class Authenticate extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();


        String url = "http://192.168.34.1:8080/SchoolWebService/rest/User/"+username+","+password;

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject c = new JSONObject(jsonStr);

                String uname = c.getString("username");
                String pword = c.getString("password");
                snackbar.setText("Authenticated").show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            snackbar.setText("Authentication Failed!").show();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

The Log.d(....); statement always returns null.

Charles
  • 112
  • 11

2 Answers2

1

What do your server logs say? Does the request even make it to the server? A Tcpdump or a Wireshark trace on the server machine would help you see what is different about the browser request and the Android request.

I haven't used HttpClinet directly in quite some time. You should consider using a library for your http requests. Here is an example using Volley, as another user suggested.

    String username = "george";
    String password = "jetson";
    String url = "http://192.168.34.1:8080/SchoolWebService/rest/User/"+username+","+password;

    Context appContext = InstrumentationRegistry.getTargetContext();
    RequestQueue queue = Volley.newRequestQueue(appContext);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
          new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {

                  Log.d("TAG", "success: " + response);

              }
          }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    queue.add(stringRequest);

Consider using digest auth, clear text passwords in the url is not a great solution, even if its a school project.

Gary Bak
  • 4,746
  • 4
  • 22
  • 39
0

Thanks guys but I finally found the solution. As @foobar commented, the makeServiceCall method was throwing an exception which I wasn't seeing so I took out the printStackTrace() and replaced it with Log.e(TAG, Log.getStackTraceString(e)); then I found out that my phone couldn't connect to my pc over the network. I was getting a connection refused error message. So I did the following things.

  1. Turned on USB tethering on my phone.
  2. Typed ipconfig from command prompt and got my IPv4 address from my USB connection 192.168.42.xxx.
  3. I replaced the ip address in my URL with this.
  4. I added Inbound and Outbound rules to my firewall on my port number and everything started working

Thanks guys

Charles
  • 112
  • 11