2017-06-21 5 views
0

私は、すべての受信データ(XML)を別のサーバに送信するjava proxyservletを作成する必要があります。 しかし、受信データをリモートサーバーに投稿するにはどうすればよいですか? Java7として、より新しいためCloseableHttpClientを使用したり、あまりにも古いバージョンのJava用のHttpClientを使用したのと同じくらい簡単Java proxyservletが別のサーバにデータを投稿する

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String server = "http://server.tld"; 
    String subURI = request.getRequestURI().split("/ProxyServlet")[1]; 
    System.out.println("ProxyServlet: " + server + subURI); 
    URL remoteServer = new URL(server + subURI); 
    HttpURLConnection connection = (HttpURLConnection) remoteServer.openConnection(); 

    //somehow apply request to remoteServer and receive response   
} 

答えて

0

最後に、私はthis articleの助けを借りて、それを解決することができます:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String server = "http://server.tld"; 
    String subURI = request.getRequestURI().split("/ProxyServlet")[1];  
    System.out.println("ProxyServlet: " + server + subURI);  
    URL remoteServerURL = new URL(server+subURI); 
    HttpURLConnection remoteServer = (HttpURLConnection) remoteServerURL.openConnection(); 
    remoteServer.setRequestMethod("POST"); 
    remoteServer.setDoOutput(true); 
    remoteServer.getOutputStream().write(readBytes(request.getInputStream())); 
    response.getOutputStream().write(readBytes(remoteServer.getInputStream())); 
} 

/** 
    * Read and return the entire contents of the supplied {@link InputStream stream}. This method always closes the stream when 
    * finished reading. 
    * 
    * @param stream the stream to the contents; may be null 
    * @return the contents, or an empty byte array if the supplied reader is null 
    * @throws IOException if there is an error reading the content 
    */ 
    private byte[] readBytes(InputStream stream) throws IOException { 
     if (stream == null) return new byte[] {}; 
     byte[] buffer = new byte[1024]; 
     ByteArrayOutputStream output = new ByteArrayOutputStream(); 
     boolean error = false; 
     try { 
      int numRead = 0; 
      while ((numRead = stream.read(buffer)) > -1) { 
       output.write(buffer, 0, numRead); 
      } 
     } catch (IOException e) { 
      error = true; // this error should be thrown, even if there is an error closing stream 
      throw e; 
     } catch (RuntimeException e) { 
      error = true; // this error should be thrown, even if there is an error closing stream 
      throw e; 
     } finally { 
      try { 
       stream.close(); 
      } catch (IOException e) { 
       if (!error) throw e; 
      } 
     } 
     output.flush(); 
     return output.toByteArray(); 
    } 
0

次に、OutPutStreamをバイト配列に読み込んで、CloseableHttpClientのInputStreamに書き込みますか?

関連する問題