-1

I have a Django endpoint:

urlpatterns = [
    path('store', views.store, name='store'),
]

And this view:

def store(request):
    x = request.POST['x']
    y = request.POST['y']
    z = request.POST['z']
    timestamp = request.POST['timestamp']
    Data(x=x, y=y, z=z, timestamp=timestamp).store()
    return HttpResponse(status=200)

I need to make an http request to that endpoint from an android phone.

I have this code right now, how I can add POST parameters?

String endpoint = "http://192.168.1.33:8000/rest/store";
try { new uploadData().execute(new URL(endpoint)); }
catch (MalformedURLException e) { e.printStackTrace(); }

private class uploadData extends AsyncTask<URL, Integer, String> {

        String result;

        protected String doInBackground(URL... urls) {
            try {
                HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
                result = urlConnection.getResponseMessage();
                urlConnection.disconnect();
            }
            catch (IOException e) { result = "404"; }
            return result;
        }

        protected void onPostExecute(String result) {
            if (result.equalsIgnoreCase("OK")) {
                ((TextView) findViewById(R.id.http)).setText("Database Online");
                ((TextView) findViewById(R.id.http)).setTextColor(Color.GREEN);
            }
            else if (result.equalsIgnoreCase("FORBIDDEN")) {
                ((TextView) findViewById(R.id.http)).setText("No user for device");
                ((TextView) findViewById(R.id.http)).setTextColor(Color.RED);
            }
            else{
                ((TextView) findViewById(R.id.http)).setText("Can't reach server");
                ((TextView) findViewById(R.id.http)).setTextColor(Color.RED);
            }
        }
    }

How I can add x,y,z and timestamp as a POST parameters?

Lechucico
  • 1,914
  • 7
  • 27
  • 60
  • https://stackoverflow.com/questions/2938502/sending-post-data-in-android?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – mudit_sen Apr 17 '18 at 16:57

3 Answers3

1

Suppose data is a jsonObject which has post parameters :

 HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
 urlConnection.setRequestMethod("POST");
 setHeaders(postConn);
 String mData = data.toString();
 if (mData != null) {
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Length", Integer.toString(mData.length()));
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(postConn.getOutputStream(), "UTF-8");
        final PrintWriter out = new PrintWriter(outputStreamWriter, true);
        out.print(mData);
        out.close();

      }
 int result = urlConnection.getResponseMessage();
  InputStream in = null;
  if (result == HttpsURLConnection.HTTP_OK) {
    in = postConn.getInputStream(); // to get result
 }
 urlConnection.disconnect();

SetHeaders would be :

private void setHeaders(final HttpsURLConnection connection) {
    connection.addRequestProperty("Content-type", "application/json");
    // Add more headers
}

Hope this helps !!

Anonymous
  • 2,184
  • 15
  • 23
0

Use Retrofit. It simplifies a lot for you.

Documentation: http://square.github.io/retrofit/

Tutorial: https://www.youtube.com/watch?v=R4XU8yPzSx0

There is hardly a reason to use anything else. Let me know if it was helpful or not.

Luís Henriques
  • 604
  • 1
  • 10
  • 30
0

Use OkHttp

add implementation 'com.squareup.okhttp3:okhttp:3.10.0' to your gradle

to send a post request use

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
   .url(url)
   .post(body)
   .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

check out the documentation here

Thankgod Richard
  • 507
  • 6
  • 16