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