I'm having this issue for posting data only, I got 401 (non-authorized) while my credential are correct! how to fix this?

ttpURLConnection urlConnection;
       IgnoreSSL();
       String url = null;
       url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
       String result = null;
       try {

           String userpass = user_name + ":" + password; //stored in the class
           String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));

           //Connect
           urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
           urlConnection.setDoOutput(true);
           urlConnection.setRequestProperty("Content-Type", "application/json");
           urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
           urlConnection.setRequestProperty("Accept", "application/json");
           urlConnection.setRequestMethod("POST");
           urlConnection.setConnectTimeout(10000);
           urlConnection.connect();
           //data
           String data = datajson.toString(); //method return json to use
           OutputStream outputStream = urlConnection.getOutputStream();
           BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
           writer.write(data);
           writer.close();
           outputStream.close();
           int responseCode=urlConnection.getResponseCode();
           if (responseCode == HttpsURLConnection.HTTP_OK) {
               //Read
               BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

               String line = null;
               StringBuilder sb = new StringBuilder();

               while ((line = bufferedReader.readLine()) != null) {
                   sb.append(line);
               }

               bufferedReader.close();
               result = sb.toString();

           }else {
               //    return new String("false : "+responseCode);
               new String("false : "+responseCode);
           }

       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

I tried in Linux with curl command It works perfectly - I got respond 200 and printed results in the screen.

0 Answers