-1

I'm just trying to get a simple conversor from °C to °F in a Server (Django) The Django Backend is ok, but I only want a simple way to get that info and print that in an Android app:

URL: 192.168.1.212:8000/c_f/4.0

And the response is:

{"far": 39.2}

I tryied, but I only find huge codes and nothing seems to work.

Cris_Towi
  • 615
  • 1
  • 13
  • 25

2 Answers2

1
class sampleService extends AsyncTask<Boolean, Boolean, Boolean> {

    @Override
    protected Boolean doInBackground(Boolean... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet del = new HttpGet("192.168.1.212:8000/c_f/4.0");
        del.setHeader("content-type", "application/json");
        try {
            HttpResponse resp = httpClient.execute(del);
            String respStr = EntityUtils.toString(resp.getEntity());
            JSONObject respJSON = new JSONObject(respStr);
            String far = respJSON.getString ("far"); //Check your type data to return in your web service.
            Log.d("Service", far);
        } catch(Exception ex) {
            Log.e("Service","Error!", ex);
        }
        return null;
    }

}

Chefes
  • 1,892
  • 18
  • 17
  • Bur where do I get the JSONObject? And what does Boolean... params means? – Cris_Towi May 13 '14 at 23:41
  • JSONObject is a library incorpored in Android. Boolean params is just beacause we need a value to execute an AsyncTask. you need to do : new sampleService().execute(true); – Chefes May 13 '14 at 23:45
  • And how can I call this class in my onClick Function in my view? – Cris_Towi May 13 '14 at 23:56
  • button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new sampleService().execute(true); } }); – Chefes May 13 '14 at 23:57
  • Anyway, that stills not working, but at least this does not crash anymore. I dont know what happens, but it stops working in the try{} block. – Cris_Towi May 14 '14 at 00:11
  • What is the Exception? – Chefes May 14 '14 at 00:18
  • Connection to http://192.168.1.212:8000 refued and Something in DefaultClientConnectionOperator. – Cris_Towi May 14 '14 at 00:46
  • That Error is because your server is not online in your network, check if you can access to webpage from the device web navigator or make ping to 192.168.1.212:8000 in your android device. – Chefes May 14 '14 at 00:51
  • This is what i get: http://stackoverflow.com/questions/23644026/fatal-exception-asynctask-3-in-json-response-for-android – Cris_Towi May 14 '14 at 01:03
0

You can use the httppost and httpClient to enable to get the response from the web

example

String getURL = "192.168.1.212:8000/c_f/4.0";

        HttpClient client = new DefaultHttpClient();  

        HttpPost httppost = new HttpPost(getURL);
HttpResponse responseGet = client.execute(httppost);  
        HttpEntity resEntityGet = responseGet.getEntity(); 
Lod.d("response", EntityUtils.toString(resEntityGet));
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63