1 16 17 package org.springframework.remoting.httpinvoker; 18 19 import java.io.ByteArrayOutputStream ; 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 import java.net.HttpURLConnection ; 23 import java.net.URL ; 24 import java.net.URLConnection ; 25 import java.util.zip.GZIPInputStream ; 26 27 import org.springframework.remoting.support.RemoteInvocationResult; 28 29 43 public class SimpleHttpInvokerRequestExecutor extends AbstractHttpInvokerRequestExecutor { 44 45 55 protected RemoteInvocationResult doExecuteRequest( 56 HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) 57 throws IOException , ClassNotFoundException { 58 59 HttpURLConnection con = openConnection(config); 60 prepareConnection(con, baos.size()); 61 writeRequestBody(config, con, baos); 62 validateResponse(config, con); 63 InputStream responseBody = readResponseBody(config, con); 64 65 return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); 66 } 67 68 76 protected HttpURLConnection openConnection(HttpInvokerClientConfiguration config) throws IOException { 77 URLConnection con = new URL (config.getServiceUrl()).openConnection(); 78 if (!(con instanceof HttpURLConnection )) { 79 throw new IOException ("Service URL [" + config.getServiceUrl() + "] is not an HTTP URL"); 80 } 81 return (HttpURLConnection ) con; 82 } 83 84 95 protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException { 96 con.setDoOutput(true); 97 con.setRequestMethod(HTTP_METHOD_POST); 98 con.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType()); 99 con.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength)); 100 if (isAcceptGzipEncoding()) { 101 con.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP); 102 } 103 } 104 105 118 protected void writeRequestBody( 119 HttpInvokerClientConfiguration config, HttpURLConnection con, ByteArrayOutputStream baos) 120 throws IOException { 121 122 baos.writeTo(con.getOutputStream()); 123 } 124 125 135 protected void validateResponse(HttpInvokerClientConfiguration config, HttpURLConnection con) 136 throws IOException { 137 138 if (con.getResponseCode() >= 300) { 139 throw new IOException ( 140 "Did not receive successful HTTP response: status code = " + con.getResponseCode() + 141 ", status message = [" + con.getResponseMessage() + "]"); 142 } 143 } 144 145 161 protected InputStream readResponseBody(HttpInvokerClientConfiguration config, HttpURLConnection con) 162 throws IOException { 163 164 if (isGzipResponse(con)) { 165 return new GZIPInputStream (con.getInputStream()); 167 } 168 else { 169 return con.getInputStream(); 171 } 172 } 173 174 180 protected boolean isGzipResponse(HttpURLConnection con) { 181 String encodingHeader = con.getHeaderField(HTTP_HEADER_CONTENT_ENCODING); 182 return (encodingHeader != null && encodingHeader.toLowerCase().indexOf(ENCODING_GZIP) != -1); 183 } 184 185 } 186 | Popular Tags |