Consuming ASP.NET Web Api from Android HttpUrlConnection and Gson

1.1k views Asked by At

Heyy everyone, I'm trying to consume a web service from Android, I did that from my Java Desktop App and it worked fine but when I tried it on Android I had a lot of errors. I already fixed the "localhost" problem with IIS express . Please Help me with that.

public void SetCloud(View v) {

    ConnectionTask task = new ConnectionTask();

    try {
        task.execute().get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /*
    Http http = HttpFactory.create(context);
    http.post("http://192.168.8.2:57888/api/Employees/AddAccount")
        .data(new AccountBag("Test123", "TestServer12","D19916F-7C51-4AD6-AC24"))
        .send();*/
}


private class ConnectionTask extends AsyncTask<Void, Void, String>{
    String responseCode = null;
    @Override
    protected String doInBackground(Void... arg0) {
      try {

        URL url = new URL("http://192.168.8.2:57888/api/Employees/AddAccount");
          //URL url = new URL("http://esprit.azurewebsites.net/api/comments");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");


        AccountBag obj = new AccountBag("Test123", "TestServer12","D19916F-7C51-4AD6-AC24"/*,"DateTime","aaa","bbbb","cccc","dddd","ffff"*/);
        Gson gson = new Gson();

        // convert java object to JSON format,
        // and returned as JSON formatted string
        String json = gson.toJson(obj);

        OutputStream os = conn.getOutputStream();
        //os.write(input.getBytes());
        os.write(json.getBytes());
        os.flush();

        /*if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }*/
        responseCode = ""+conn.getResponseCode();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }
    return responseCode;

    }
    }

    protected void onPostExecute(String result) {
               // result is what you got from your connection
//ConnectionTask.responseCode.setText(result);

    }

}
1

There are 1 answers

4
Vishva Nath Singh On
public class RestAddGroupUser extends AsyncTask<List<UserGroup>,Void,String> {
private  RestService lRestService;
private String url;
group_action activity;
ArrayList<LatLong> mParam;

public RestAddGroupUser(Activity activity) {
    url= GlobalData.baseURL + "AddGroupuser";
    this.activity = (group_action)activity;
}

protected void onPreExecute(){
}
String result = "";

protected String doInBackground(List<UserGroup>... params) {

    try {

        StringEntity en;
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        Gson gson = new Gson();
        String jsonobj=gson.toJson(params[0]);
        jsonobj=jsonobj.substring(1, jsonobj.length()-1);
        en= new StringEntity(jsonobj,"UTF-8");
        en.setContentType("application/json");

        // Add parameters
        httppost.setEntity(en);
        String jsonobject=gson.toJson(params[1]);
        jsonobject=jsonobject.substring(1, jsonobj.length()-1);
        en= new StringEntity(jsonobject,"UTF-8");
        en.setContentType("application/json");

        // Add parameters
        httppost.setEntity(en);
        httppost = ServiceUtils.SetPostRequestHeader(httppost,activity);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inStream = entity.getContent();
            result = convertStreamToString(inStream);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
public void onPostExecute(String result){

    Gson gson =new Gson();
    boolean status = false;


}
public static String convertStreamToString(InputStream is){
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;

    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}