0

I have created my own server and I'd like to create Android application that would send request with data to it. I have already tested server with postman.

I tried to create POST request with use of this answer: https://stackoverflow.com/a/2938787/7143020 However unfortunately it seems that there may be no request send.

Related code is below:

@Override
protected String doInBackground(String... strings) {
    String urlString = strings[0];
    String data = strings[1];
    OutputStream out = null;
    OutputStream outputStream;

    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        outputStream = urlConnection.getOutputStream();
        out = new BufferedOutputStream(urlConnection.getOutputStream());

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(data);
        writer.close();
        out.close();

        urlConnection.connect();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

I tried with debugger and value for out was null so trouble may be related to

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

In AndroidManifest.xml I have two permissions added:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How can I resolve this issue?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
mateuszs
  • 165
  • 1
  • 1
  • 10
  • 1
    The posted answer seems to be correct but you'll be far better off using 3rd party library like Retrofit. It takes very little effort to understand how it works but makes you work much more efficiently. – Ernest Zamelczyk Mar 12 '19 at 17:20
  • @ErnestZamelczyk I tried with one OutputStream and unfortunately issue with null persists. I also tried with OkHttp library before but it seems that request also did not reach the server. – mateuszs Mar 12 '19 at 17:24
  • Then there might be some issue with your server implementation. Are you using correct url? Is the TLS enabled on your server? Depending on which Android version you're using TLS might require more work to enable. – Ernest Zamelczyk Mar 12 '19 at 17:28
  • OH I see that now. You forgot to flush your writer. Add `writer.flush()` after `writer.write(data)` – Ernest Zamelczyk Mar 12 '19 at 17:32
  • @ErnestZamelczyk url is confirmed to be correct, writer.flush() also does not work (if I'm not mistaken flush is included in close), as for TLS - if I'm not mistaken I have protocol of TLS 1.2, I am using android API 23. – mateuszs Mar 12 '19 at 18:37

0 Answers0