java.io.IOException:服务器返回HTTP响应代码:403表示URL

时间:2015-08-06 03:30:47

标签: java

使用java代码尝试发送HTTP POST请求。 但是我得到了

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

    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();
      }

}

但是当我在休息控制台尝试时,它正常运行。

REST控制台的请求标头

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

回应机构

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

我的java代码有什么问题。

1 个答案:

答案 0 :(得分:0)

由于这是一个POST调用,我相信在下面添加语句可以解决问题。

urlConnection.setRequestMethod("POST");