0

hi im new to AsyncTask and i need to send data to API server. im doing the connection and im stuck here. i read about the AsyncTask and this is the code that i've seen. first thing is if i determine if the device is connected, it will send data on the URL given, else. it will send thru SMS

public class SendData extends AsyncTask <String, Void, Boolean> {
    DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
    Date date = new Date();
    String datefinal = dateFormat.format(date).toString();
    String url = "http://192.168.1.212/mobile_alerts_api.php?location=&msg=&datetime=&id=";


    @Override
    protected Boolean doInBackground(String... urls) {
        try{
            HttpGet httppost = new HttpGet(url);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONObject jsono = new JSONObject(data);
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {

            e.printStackTrace();
        }
        return false;
    }
    protected void onPostExecute(Boolean result) {

    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I suppose you have not heard of Retrofit or Volley, have you? – OneCricketeer Oct 16 '17 at 02:22
  • 1
    Anyways, I don't think `HttpGet` is the correct class if you want to use a POST – OneCricketeer Oct 16 '17 at 02:22
  • @cricket_007 yes i never heard of it atm –  Oct 16 '17 at 02:23
  • Might want to read the documentation for a bit. https://developer.android.com/training/volley/index.html You're looking for a `JsonObjectRequest` class – OneCricketeer Oct 16 '17 at 02:25
  • @cricket_007 okay thanks –  Oct 16 '17 at 03:51
  • Please note that the HttpEntity and related Apache classes are "deprecated" to Android. HttpURLConnection is the Java built-in class for HTTP usage. Volley or Okhttp3 are easy libraries to send String/JSON data. Use Retrofit if you additionally need to parse JSON into/from actual Java objects – OneCricketeer Oct 16 '17 at 06:12

2 Answers2

0

Use:

HttpPost httppost = new HttpPost(url);

instead of

HttpGet httppost = new HttpGet(url);

Get is used to get data from the server. Post is used to send data to the server

Syam Sundar K
  • 129
  • 1
  • 12
0
        String json=yourJsonData;
     StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");

Then execute the httppost in your async task class

himel
  • 500
  • 5
  • 14