0

I try to send a json object to a distant server using HttpURLConnection. but this error was displayed

"Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 401
at TestSendSMS.main(TestSendSMS.java:40)"

I didn't know what's the problem.What's wrong in this code? Any help

 try {
        /*
         * JSONObject jsonParam = new JSONObject();
         * jsonParam.put("-----","----"); jsonParam.put("----","-----");
         * jsonParam.put("-----","-----");
         */
        String input = "{\"------\":\"------\",\"-----\":\"------\",\"------\":\"-----\"}";
        System.out.println("JsonObj " + jsonParam);

        URL myURL = new URL("-----------------------");
        HttpURLConnection myURLConnection = (HttpURLConnection) myURL
                .openConnection();

        myURLConnection.setDoOutput(true);
        myURLConnection.setDoInput(true);
        myURLConnection.setChunkedStreamingMode(0);
        myURLConnection.setUseCaches(false);
        myURLConnection.setConnectTimeout(10000);
        myURLConnection.setReadTimeout(10000);
        myURLConnection.setRequestProperty("Content-Type",
                "application/json");
        myURLConnection.setRequestProperty("Accept", "application/json");

        OutputStream os = myURLConnection.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (myURLConnection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + myURLConnection.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (myURLConnection.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        myURLConnection.disconnect();
    } catch (MalformedURLException e) {
        System.out.println("error1");
    }

    catch (IOException e) {
        System.out.println("error2");
    }
Vivek Singh
  • 2,047
  • 11
  • 24
Tommy
  • 55
  • 1
  • 14

1 Answers1

1

HTTP Error 401 is an authentication problem.

You need to authenticate to the server when sending the request.

This topic may help you authenticate with URLConnection :

How to handle HTTP authentication using HttpURLConnection?

Community
  • 1
  • 1
Arnaud
  • 17,229
  • 3
  • 31
  • 44