2012-05-04 3 views
4

파일 내용을 포함하는 문자열이 아닌 파일의 서버 측에서 다중 요청 URL을 호출하는 방법을, 나는 그것을 업로드 할 다중 POST 요청으로 다른 URL을 호출 할 필요가 XML 파일로.는 내 서블릿에서 문자열로 XML 파일의 내용이

그것을 할 수있는 방법이 있나요?

는 지금까지 내가 아래

private def createConfiguration(def sessiontoken) 
{ 
    /*reqParams is request.getParameterMap(), fileParams is again a map*/ 
    def charset = "UTF-8"; 
    def query = String.format("emailaddress=%s&projectid=%s&cfgname=%s&cfgdesc=%s&cfgfile=%s", 
     URLEncoder.encode(sessiontoken, charset), 
     URLEncoder.encode(reqParams.c_Cfgname[0], charset), 
     URLEncoder.encode(reqParams.c_Cfgdesc[0], charset), 
     URLEncoder.encode(reqParams.c_Cfgtype[0], charset), 
     URLEncoder.encode(reqParams.CFGFILE[0], charset),) 

    URLConnection connection = new URL(fileParams.login).openConnection() 
    connection.setDoOutput(true) 
    connection.setRequestProperty("Accept-Charset", charset) 
    connection.setRequestProperty("Content-Type", "multipart/form-data;charset=" + charset) 
    try { 
     connection.getOutputStream().write(query.getBytes(charset)) 
    } 
    finally { 
     connection.getOutputStream().close() 
    } 
    InputStream response = connection.getInputStream() 
    def xmlString=response.getText() 
    xmlString 
} 

가 가져온 예외가 뭘 오전입니다

심각한 서버 : 예외를 때 java.io.IOException를 던졌다 RedirectRequest 서블릿의 Servlet.service() 반환 된 HTTP 응답 코드 : 800에 대한 URL : http://abhishek157:10070/project/create.action at sun.net.www.protocol.http.HttpURLConnection.getInputStream (알 수없는 소스) at sun.net.www.protocol.http.HttpURLConnection $ getInputStream.call (Unkn 자신의 출처) . .

업데이트를 얻었다

이 매우 유용한 link by BalusC 그래서 나는 그것을 사용.

private def getStreamFromString(str) 
{ 
    // convert String into InputStream 
    InputStream is = new ByteArrayInputStream(str.getBytes()) 
    is 
} 

private def createConfiguration(def sessiontoken) 
{ 


    println "ok good $sessiontoken" 
    def charset = "UTF-8" 
    def boundary = Long.toHexString(System.currentTimeMillis()) 
    def CRLF = "\r\n" 
    String param = "value" 

    URLConnection connection = new URL(fileParams.create).openConnection() 
    println fileParams.create 
    connection.setDoOutput(true) 
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 
    PrintWriter writer = null 
    try { 

     OutputStream output = connection.getOutputStream() 
     writer = new PrintWriter(new OutputStreamWriter(output, charset), true) 

     // Sending normal param. 
     writer.append("--" + boundary).append(CRLF) 
     writer.append("Content-Disposition: form-data; name=\"sessiontoken\"$CRLF$CRLF$sessiontoken").append(CRLF) 
     //writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF) 
     writer.append(CRLF) 
     writer.append(param).append(CRLF).flush() 

     writer.append("--" + boundary).append(CRLF) 
     writer.append("Content-Disposition: form-data; name=\"cfgname\"$CRLF$CRLF${reqParams.c_Cfgname[0]}").append(CRLF) 
     //writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF) 
     writer.append(CRLF) 
     writer.append(param).append(CRLF).flush() 

     writer.append("--" + boundary).append(CRLF) 
     writer.append("Content-Disposition: form-data; name=\"cfgdesc\"$CRLF$CRLF${reqParams.c_Cfgdesc[0]}").append(CRLF) 
     //writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF) 
     writer.append(CRLF) 
     writer.append(param).append(CRLF).flush() 

     writer.append("--" + boundary).append(CRLF) 
     writer.append("Content-Disposition: form-data; name=\"cfgenv\"$CRLF$CRLF${reqParams.c_Cfgtype[0]}").append(CRLF) 
     //writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF) 
     writer.append(CRLF) 
     writer.append(param).append(CRLF).flush() 

     // Sending xml file. 
     writer.append("--" + boundary).append(CRLF) 
     writer.append("Content-Disposition: form-data; name=\"cfgfile\"; filename=\"" + reqParams.FILENAME[0] + "\"").append(CRLF) 
     writer.append("Content-Type: text/xml; charset=" + charset).append(CRLF) 
     writer.append(CRLF).flush() 
     BufferedReader reader = null 
     try { 
      reader = new BufferedReader(new InputStreamReader(getStreamFromString(reqParams.CFGFILE[0]), charset)) 
      for (String line; (line = reader.readLine()) != null;) { 
       writer.append(line).append(CRLF) 
      } 
     } 
     catch(Exception e) { 
      e.printStackTrace() 
     } 
     finally { 
      if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
     } 
     writer.flush(); 
     writer.append("--" + boundary + "--").append(CRLF) 
    } 
    finally { 
     if (writer != null) writer.close(); 
    } 
    InputStream response = connection.getInputStream() 
    def xmlString=response.getText() 
    xmlString 
} 

콘솔에

나는

을 수행

http://abhishek157:10070/project/create.action
를 얻을 수 있지만, 모든 http://abhishek157:10070/project/create.action

어떤 도움을 치는되지 않는 이유는 무엇입니까?

더 많은 업데이트

(I는 웹 브라우저에서 파일을 선택 HTML 양식에서 작업) 실제 요청 피들러의 실제 요청에서 일치 후

-----------------------------7dcf4d30e8a 
Content-Disposition: form-data; name="sessiontoken" 

4611685684744086913 
-----------------------------7dcf4d30e8a 
Content-Disposition: form-data; name="cfgname" 

sadf 
-----------------------------7dcf4d30e8a 
Content-Disposition: form-data; name="cfgdesc" 

sadf 
-----------------------------7dcf4d30e8a 
Content-Disposition: form-data; name="cfgenv" 

Production 
-----------------------------7dcf4d30e8a 
Content-Disposition: form-data; name="cfgfile"; filename="C:\Simon\xmls\agentind.xml" 
Content-Type: text/xml 

<?xml version="1.0" encoding="UTF-8"?> and so on... 

업데이트 PARAMS 부분입니다. 기능 createConfiguration 참조

(서블릿에서 create.action를 호출하는 동안)

예외 인출 : 나는 create.action에 PARAMS를 전송하기 전에 서블릿 체크, 모두가 PARAMS의 유효

java.lang.NumberFormatException: null 

아무도 없습니다 서버에서 읽으면 모두 null이됩니다. 문제가 어디입니까? 도와주세요. 업데이트 된 코드에서

+1

http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java –

+0

시도해 보겠습니다. HttpClient 4.0 – abi1964

+0

연결을 설정해보십시오.setDoInput (true) aswell – jontro

답변

3

, 당신은 실제로 HTTP 요청을 보내 (그리고 HTTP 응답을 검색하는) connection.getInputStream(); 전화를 잊어 버렸습니다.

+0

감사합니다. 아직 일부 예외 (java.lang.NumberFormatException : null)가 발생하고 있습니다. 어딘가에 논리적 인 오류가있을 수 있습니다. 따라서 돌아올 것이지만 여러 부분으로 구성된 괜찮은 요청입니다. ? – abi1964

+0

여기 저기에 Groovy 구문을 사용하고 있으므로이를 확인할 수 없습니다. 예를 들어'$ CRLF' 주위의 공백이 중요한지 잘 모르겠습니다. 요청 매개 변수를 숫자로 구문 분석 할 때 예외가 서블릿 측에서 발생합니다. 그렇다면, 그 공간은 명백하게 정말로 중요합니다. – BalusC

+0

'공백'과 같은 느낌의 자바에서 동등한 코드를 제공하면 도움이 될까요? & CRLF가 지저분 해지고 있습니까? 귀하의 [링크] (http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests)에서 나는 예 : name = "sessiontoken"그러나 실제 sessiontoken 값과'CRLF'를 어디에 넣어야하는지. Groovy에서'$ CRLF'는 큰 따옴표 안에'CRLF'의 값을 얻습니다. – abi1964

관련 문제