1

Using java code am trying to send HTTP POST request. But am getting

 java.io.IOException: Server returned HTTP response code: 403 for URL

code

    try {

       String webPage = "https://testweb/test.apk?overwrite=true --data-binary @app0720.apk";
       String name = "testname";
       String password = "cpaad4%675c";

       String authString = name + ":" + password;
       System.out.println("Auth string: " + authString);            

       Base64 b = new Base64();
        String authStringEnc = b.encodeAsString(new String(authString).getBytes());

       System.out.println("Base64 encoded auth string: " + authStringEnc);

       URL url = new URL(webPage);
       URLConnection urlConnection = url.openConnection();                         
       urlConnection.addRequestProperty("Authorization", "Basic " + authStringEnc);
       urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36");
       urlConnection.addRequestProperty("Accept", "application/octet-stream");
       urlConnection.connect();

       InputStream is = urlConnection.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       int numCharsRead;
       char[] charArray = new char[1024];
       StringBuffer sb = new StringBuffer();
       while ((numCharsRead = isr.read(charArray)) > 0) {
        sb.append(charArray, 0, numCharsRead);
       }
       String result = sb.toString();

       System.out.println("---------------------------------------------");
       System.out.println("Response from the server: " + result);

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

}

but when i tried in rest console it is getting properly.

Request header from REST Console

Accept: application/octet-stream
Authorization: Basic XXXXGHuIOIUO6hndhfhrjt
Connection: keep-alive
Content-Type: application/xml
Origin: chrome-extension: //rest-console-id
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36

Response body

Request Url: https://testweb/test.apk?overwrite=true --data-binary @app0720.apk
Request Method: POST
Status Code: 200
Params: {}

whats wrong with my java code.

Psl
  • 3,830
  • 16
  • 46
  • 84

1 Answers1

0

Since this is a POST call, I believe adding below statement should solve the problem.

urlConnection.setRequestMethod("POST");
Shishir Kumar
  • 7,981
  • 3
  • 29
  • 45
  • yes i added this part also..am getting respose code 400 – Psl Aug 06 '15 at 04:10
  • Response code 400 means that request could not be understood by the server due to malformed syntax. Cross-check the data which you are posting using this `POST` call. – Shishir Kumar Aug 06 '15 at 04:23
  • But when i tried thorugh rest console am getting response code 200 – Psl Aug 06 '15 at 04:29