1

Yes, there are many questions out there like this. Most are old, and bring up compile errors in android studio though.

I want to make a simple post request, and send json encoded data. I am a complete java n00b, so please bear with me. Currently taking from this question: Sending json object via http post method in android

Here is what I have now:

try {
        URL url = new URL("https://myURL.com"); 
        String type = "application/json";
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Type", type); 
        httpURLConnection.connect();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("myKey", "myValue");

        DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
        wr.writeBytes(jsonObject.toString());
        wr.flush();
        wr.close();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

I am calling this method in onCreate in my MainActivity.java file. It compiles with no errors, but when I run it, it crashes and I see the "your app has stopped" alert. What am I doing wrong?

Community
  • 1
  • 1
jjjjjjjj
  • 4,203
  • 11
  • 53
  • 72

0 Answers0