2012-05-03 9 views
0

나는이 내 서블릿에 HTTP 호출을 시도 다음 코드 :서블릿에 액세스하고 첨부 파일을 다운로드하는 방법은 무엇입니까?

try { 
     // Construct data 
     String data = URLEncoder.encode("rpt_type", "UTF-8") + "=" + URLEncoder.encode(reportType, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_project", "UTF-8") + "=" + URLEncoder.encode(reportProject, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_mrv_creator", "UTF-8") + "=" + URLEncoder.encode(reportMrvCreator, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_gi_recipient", "UTF-8") + "=" + URLEncoder.encode(reportGiRecipient, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_plant", "UTF-8") + "=" + URLEncoder.encode(reportPlant, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_sloc", "UTF-8") + "=" + URLEncoder.encode(reportStorageLoc, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_gi_no", "UTF-8") + "=" + URLEncoder.encode(reportGiNo, "UTF-8"); 
     data += "&" + URLEncoder.encode("date_sap_gi_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateGiFrom, "UTF-8"); 
     data += "&" + URLEncoder.encode("date_sap_gi_to", "UTF-8") + "=" + URLEncoder.encode(reportDateGiTo, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_partno", "UTF-8") + "=" + URLEncoder.encode(reportPartNo, "UTF-8"); 
     data += "&" + URLEncoder.encode("rpt_so_no", "UTF-8") + "=" + URLEncoder.encode(reportSvcOrderNo, "UTF-8"); 
     data += "&" + URLEncoder.encode("date_scan_fr", "UTF-8") + "=" + URLEncoder.encode(reportDateScanFrom, "UTF-8"); 
     data += "&" + URLEncoder.encode("date_scan_to", "UTF-8") + "=" + URLEncoder.encode(reportDateScanTo, "UTF-8"); 
     System.out.println("[data]\n" + data); 

     // Send data 
     String urlString = "http://localhost:8080/aerobook/GIStatusReportDownload?" + data; 
     System.out.println("[url] " + urlString); 
     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 
     //conn.setDoOutput(true); 
     //OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     //wr.write(data); 
     //wr.flush(); 

     // Get the response 
     BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     String line; 
     while ((line = rd.readLine()) != null) { 
      System.out.println(line); 
     } 
     //wr.close(); 
     rd.close(); 
    } catch (Exception e) { 
    } 

내 디버그 출력 : 내 서블릿에

[data] 
rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012 
[url] http://localhost:8080/aerobook/GIStatusReportDownload?rpt_type=d&rpt_project=aaa&rpt_mrv_creator=bbb&rpt_gi_recipient=ccc&rpt_plant=ddd&rpt_sloc=eee&rpt_gi_no=fff&date_sap_gi_fr=02%2F05%2F2012&date_sap_gi_to=03%2F05%2F2012&rpt_partno=ggg&rpt_so_no=hhh&date_scan_fr=26%2F05%2F2012&date_scan_to=31%2F05%2F2012 

(위의 코드는 별도의 파일에) 나는 다운로드 Excel 파일을 생성합니다

res.setContentType(sContentType); 
    res.setHeader("Content-Disposition", "attachment;filename=\"" + sExcelFileName + "\""); 
    OutputStream oOutStrm = res.getOutputStream(); 
    wbBook.write(oOutStrm); 
    oOutStrm.close(); 

여기 내 문제는 (위의 디버그 출력 참조) 내 코드에 의해 생성 된 URL에서, 내 서블릿 a를 액세스 할 수있다 그러면 Save-As 대화 상자를 얻을 수 있습니다.

내 코드 내에서 사용하기 위해 생성 된 파일의 내용을 얻고 싶습니다. 내 코드에서 바이트 스트림이나 다른 형식으로 첨부 파일을 가져올 수있는 방법이 있습니까?


편집 # 3 : 또한 가까운 그 전에 oOutStrm.flash()를 호출 할 필요가 아무것도의 OutputStream에 기록되었는지 여부를 상단

+0

브라우저에서 URL을 확인 했습니까? –

+0

예. 위의 코드 섹션에서'System.out.println (data);'문자열'key1 = value1 & key2 = value2'을 생성했습니다. 내가 한 일은 내가 "?"라고 덧붙였다. 내 URL에이 문자열이옵니다. 내가 얻은 결과는'http : // localhost/MyProject/MyServlet? key1 = value1 & key2 = value2'입니다. 이 주소를 브라우저 주소창에 입력하면 엑셀 파일을 다운로드 할 수있었습니다. 내 코드에서 Excel 파일의 내용을 가져오고 싶지만 지금까지 작동하지 않습니다. – ohseekay

+0

확인. 이 샘플을 확인하십시오. http://www.roseindia.net/java/example/java/io/file-url-download.shtml –

답변

0

I want to get the contents of the excel file on my code, but so far it's not working.

보십시오.
콘텐츠를 입력 스트림에서 HSSFWorkbook 개체로 변환하고 싶습니다.
다음 코드 스 니펫이 도움이 될 것입니다.

java.net.URLConnection conn = url.openConnection(); 
java.io.InputStream is = conn.getInputStream(); 
org.apache.poi.hssf.usermodel.HSSFWorkbook workBook = new org.apache.poi.hssf.usermodel.HSSFWorkbook(is); 
System.out.println("Number of Sheets: " + workBook.getNumberOfSheets()); 
org.apache.poi.hssf.usermodel.HSSFSheet sheet = workBook.getSheetAt(0); 
System.out.println("Sheet Name: " + sheet.getSheetName()); 

// rest of your code to handle the captured workBook 
// cheers 
0

확인 wbBook.write(oOutStrm);을 청소.

+0

나는 데이터가 기록되어 있다고 확신한다. 내 질문에 언급했듯이 URL을 통해 내 서블릿에 액세스하면 다른 이름으로 저장 대화 상자가 나타나 파일을 저장할 수 있습니다. 그러나이 코드를 복제 할 수는 없습니다. – ohseekay

+0

당신은이 URL URL을 url = 새로운 URL ("http : // localhost/MyProject/MyServlet");을 매개 변수없이 코드에서 브라우저에 입력 한 것과 같지 않게 보냅니다. – user1335794

+0

'conn.setDoOutput (true); 다음의 세 줄은 내 서블릿에 데이터를 보내도록되어 있습니다, 그렇지 않습니까? 아니면 여기에 뭔가 빠졌나요? – ohseekay

1

브라우저에 URI를 입력하면 GET 요청이 수행됩니다. 그러나 클라이언트 Java 코드는 POST 요청을 생성하고 URI가 아닌 본문에 매개 변수를 보냅니다.

HTTP 추적을보고 비교할 수 있습니다.

+0

이것은 합리적으로 들립니다! HTTP 추적을 수행하는 방법을 모르겠지만 Java 코드에서 GET 요청을 수행하는 방법은 무엇입니까? – ohseekay

+0

Re : edit # 2, 제 코드가 지금 GET 요청을하고 있다고 생각하지만 아직 작동하지 않습니다. – ohseekay

0

문제가 OutputStream oOutStrm = res.getOutputStream();에있는 것으로 의심됩니다.

나는 resHttpServletResponse이고 응답에서 이진 데이터를 쓰는 데 적합한 ServletOutputStream을 반환합니다. 서블릿 컨테이너가 API

그래서 이진 데이터

확인을 인코딩하지 않는, 그래서 filename을 제외하고 아무것도 점점되지 않을 수 있습니다.

서블릿에서 나는 코드에서 오류를 발견하지

FileOutputStream stream = new FileOutputStream("c:/excel/Book1.xls"); 
workBook.write(stream); 
+0

불행히도 저는 어떤 이유로 인해 서블릿을 변경할 수 없습니다 : ( – ohseekay

+0

수정 된 답변 확인. OutputStream에 무엇인가 쓸 수 없다면 출력으로 아무것도 얻지 못할 것입니다. –

+0

무슨 뜻인지 모르겠지만 지금은'wbBook.write (oOutStrm);'가 작동하고, 내용 유형은'application/ms-excel '. 서블릿 코드는 많은 어린이 클래스에 상속되므로 코드 변경을 정당화하는 것은 매우 어렵습니다. – ohseekay

관련 문제