쓰 게시 데이터 중 하나에서 java servlet 다른
문제
내가 하려고 쓰기 servlet 를 보낼 것입니다 XML 파일(xml 포맷된 문자열)다른블릿을 통해 게시합니다.(필수적인 비 xml 을 생성하는 코드로 대체"안녕하세요")
StringBuilder sb= new StringBuilder();
sb.append("Hello there");
URL url = new URL("theservlet's URL");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "" + sb.length());
OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
이것이 원인 서버 오류이고,두 번째블릿지 않 호출됩니다.
해결책
이 종류의 것은 훨씬 더 쉽게 라이브러리를 사용하여 다음과 같 HttpClient.도 게시 XML 코드 예제:
PostMethod post = new PostMethod(url);
RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
다른 팁
내가 사용하는 것이 좋습니다 Apache HTTPClient 대기 때문에,그것은 좋습니다.
하지만 이를 해결하기 위해 현재 문제점:보 connection.setDoOutput(true);
후에 당신이 열린 연결합니다.
StringBuilder sb= new StringBuilder();
sb.append("Hello there");
URL url = new URL("theservlet's URL");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "" + sb.length());
OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
의 내용 HTTP post 업로드스트림 및 그것의 메커니즘하지 않는 것이 무엇을 기대합니다.할 수 없습니다 단지 작성 파일로 콘텐츠를 게시하기 때문에,게시물은 아주 특정 RFC 표준 방법에 대한 데이터에 포함되는 게시물을 요청하게 전송할 수 있습니다.그것은 단지 포맷의 콘텐츠 자체이지만,그것은 또한 메카닉의 방법은"작성된"을 outputstream.시간이 많이 글은 이제 작성에 덩어리.당신이 볼의 소스 코드는 아파치의 HTTPClient 당신은 어떻게 볼 수를 기록할 수 있습니다.
이 있는 단점을 가진 콘텐츠의 길이 결과적으로 있기 때문에,내용의 길이는 증가에 의해 작은 수를 식별하는 덩어리 및 임의의 작는 일련의 문자로 구분한 각각의 덩어리를 그대로 기록합니다.의 일부에서 보는 다른 방법을 설명하는 새로운 자바 버전의 HTTPURLConnection.
http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode(int)
알지 못하는 경우 당신이 무엇을 하고 싶지 않아요 배우고,그것을 다루는 추가 종속성과 같은 아파치 HTTPClient 정말 끝이 훨씬 쉽기 때문에 그것은 초록은 모든 복잡성과 작동합니다.
을 사용하는 것을 잊지 마십시오:
connection.setDoOutput( true)
하려는 경우에 보내는 출력된다.