2017-01-05 1 views
3

postFile()을 호출하면 HTTP 게시물이 만들어 지지만 "요청"문자열은 서버에 도착하지 않습니다. 호스트는 요청을 수신하고이 경우에는 요청이 비어 있음을의 L하는 400을 보냄니다.Java HTTP POST 요청 문자열이 도착하지 않습니다.

모든 예는 이것이 충분해야 함을 보여줍니다.

무엇이 문제입니까?

public static void postFile(
    String host, 
    String beaconId, 
    String fileName, 
    String base64File) 
    throws IOException { 

    StringBuilder request = new StringBuilder(base64File.length() + fileName.length() + 256); 
    request.append("{\n"); 
    request.append("\"beaconId\": \"" + beaconId + "\",\n"); 
    request.append("\"fileName\": \"" + fileName + "\",\n"); 
    request.append("\"fileContent\": \"data:application/pdf;base64," + base64File + "\"\n"); 
    request.append("}"); 

    URL url = new URL("https://" + host + "/_ah/api/service/v1/files/add"); 
    //TODO ignore cert problems for now! 
    TrustManager[] trustAllCerts = new TrustManager[] { 
     new X509TrustManager() { 

      public X509Certificate[] getAcceptedIssuers() { 

       return null; 
      } 

      public void checkClientTrusted(
       X509Certificate[] certs, 
       String authType) {} 

      public void checkServerTrusted(
       X509Certificate[] certs, 
       String authType) {} 
     } 
    }; 
    SSLContext sslContext; 
    try { 
     sslContext = SSLContext.getInstance("SSL"); 
    } 
    catch (NoSuchAlgorithmException e) { 
     throw new RuntimeException(e); 
    } 
    try { 
     sslContext.init(null, trustAllCerts, new SecureRandom()); 
    } 
    catch (KeyManagementException e) { 
     throw new RuntimeException(e); 
    } 
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
    try { 
     conn.setSSLSocketFactory(sslContext.getSocketFactory()); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     conn.setDoOutput(true); 
     try(OutputStream os = conn.getOutputStream()) { 
      os.write(request.toString().getBytes("UTF-8")); 
      os.flush(); 
      int respCode = conn.getResponseCode(); 
      String respMsg = conn.getResponseMessage(); 
      if (respCode != HTTP_CREATED) { 
       throw new RuntimeException("HTTP error : " + conn.getResponseCode() + "\n" + respMsg); 
      } 
      String response = IOUtils.toString(conn.getInputStream(), "UTF-8"); 
      String[] lines = response.split("\n"); 
      if (lines.length != 6) { 
       throw new RuntimeException("Invalid response : " + response); 
      } 
      if (!lines[2].contains("\"success\": true,")) { 
       throw new RuntimeException("Post failed : " + response); 
      } 
     } 
    } 
    finally { 
     conn.disconnect(); 
    } 
} 

답변

0

응용 프로그램 /의 경우 내가

request.append("beaconId=" + beaconId + "&"); 
    request.append("fileName=" + URLEncoder.encode(fileName, "UTF-8") + "&"); 
    request.append("fileContent=data:application/pdf;base64," + base64File); 

양식을 사용할 필요가 x-www-form-urlencoded를.