0

I am trying to create my first android application that utilizes a REST api. My api is written in Node.JS and has already been tested using Postman, however, I am having trouble sending JSON data to my api.

    @Override
    protected String doInBackground(String... params) {

        String data = "";
        String urlName = params[0];

        HttpURLConnection httpURLConnection = null;
        try {

            httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(params[1]);
            wr.flush();
            wr.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

        return data;
    }

I always reach the line that declares and initializes my DataOutputSteam and doesn't execute the code. I am not even getting a log that my Virtual device has visited my server at all.

I have included in the manifest XML both of these already.

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
2000rs25
  • 47
  • 6
  • Are you getting any errors? If possible, could you share logcat output? – Christilyn Arjona Dec 18 '19 at 23:17
  • Yes I am getting some errors such as: W/System.err: android.os.NetworkOnMainThreadException, W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90), W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126), W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258), I/Choreographer: Skipped 333 frames! The application may be doing too much work on its main thread. – 2000rs25 Dec 19 '19 at 00:00

2 Answers2

0

Based on your logs, you're hitting a NetworkOnMainThreadException and that's preventing the network request from being executed (it's going into your catch block instead). This suggests you aren't calling your AsyncTask correctly - ensure that you're calling execute instead of calling doInBackground. See also here for more information on this general pattern.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
0

Try this, it is for POST method that accept 2 parameter email and password. Change it based on your requirement

URL url = new URL(Login_url);
            HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept" , "application/json");
            conn.connect();

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("email", "Your_Email")
                    .appendQueryParameter("password","Your_Password");
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query); 
            writer.flush();
            writer.close();
            os.close();
            code = conn.getResponseCode();

            Log.e("Result", code + "");

            InputStream input = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            StringBuilder result = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {

                result.append(line);

            }

            Log.e("Result",result.toString());
L2_Paver
  • 596
  • 5
  • 11