-1

I'm struggling to find good examples on how to POST key value pairs to a URL with Android in Java.

Here is what the Android documentation says (and pretty much every other example):

URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

try {
    urlConnection.setDoOutput(true);
    urlConnection.setChunkedStreamingMode(0);

    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
    writeStream(out);

    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);

} finally {
    urlConnection.disconnect();
}

How do I implement writeStream?

Many other examples with POST put the parameters in the URL (a=1&b=2&c=3...), but then I could just use GET (?). And I don't want to place the parameters in the URL because that increases the chance of sensitive information to be logged on the server side.

Chrome POSTs data as such (body):

------WebKitFormBoundaryyr0AtYZxcOCCp7hA
Content-Disposition: form-data; name="parameterNameHere"

valueHere
------WebKitFormBoundaryyr0AtYZxcOCCp7hA--

Does the Android framework support this? If not, are there any good libraries?

EDIT:

This is not a duplication of what was suggested. What was suggested does in no way answer the question, in that it does not show how to post with parameters, which is what this question is about.

HelloWorld
  • 3,381
  • 5
  • 32
  • 58
  • 2
    Possible duplicate of [Sending POST data in Android](https://stackoverflow.com/questions/2938502/sending-post-data-in-android) – Andrei Sfat Jul 18 '18 at 20:25
  • @sfat Not a duplication. If you read my question, surely you would see that I wanted to post parameters. – HelloWorld Jul 18 '18 at 20:27
  • `And I don't want to place the parameters in the URL because that increases the chance of sensitive information to be logged on the server side.` Then put them in the request body. I don't understand what you mean by `post parameters`. In the given url, it is passed in the body – Andrei Sfat Jul 18 '18 at 20:29
  • Yes, I want to place them in the request body. My question is: How do I do that? In the given url, there is only data. Not parameters. – HelloWorld Jul 18 '18 at 20:30
  • https://www.journaldev.com/13629/okhttp-android-example-tutorial#okhttp-android-post-example I would say don't go with the `HttpURLConnection`. It's pretty low level in regards to interacting with HTTP. Go with something like in the example, as OkHttp or something similar. – Andrei Sfat Jul 18 '18 at 20:36

1 Answers1

1

There are many libraries out there that would help you achieve this. One of the libraries I use the most is OkHTTP. Include this library in your gradle and check the post from 'mauker' for an example on how to post

How to use OKHTTP to make a post request?

MikeSli
  • 927
  • 2
  • 14
  • 32