JavaのServlet内で他のURLからデータを取得してそのまま、レスポンスを出力するためのコードサンプルです。
使っているのはJavaの標準ライブラリのみなので、移植性は高いと思います。googleの提供しているライブラリやApacheのcommonsのライブラリを使うともう少しコード量は減らせると思います(特に汎用的なcopyメソッドの部分)。
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
public class ServletUtils {
private static final int _20K_BYTES = 20480;
public static void fetchUrlAndDirectlyRespond(HttpServletResponse resp, String contentType, String urlStr)
throws MalformedURLException, IOException, URISyntaxException
{
URL url = new URI(urlStr).toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
ServletOutputStream os = resp.getOutputStream();
resp.setContentType(contentType);
copy(connection.getInputStream(), os, ServletUtils._20K_BYTES);
connection.disconnect();
}
public final static void copy(InputStream is, OutputStream os, int bufsize) throws IOException {
byte[] buffer = new byte[bufsize];
try{
for (int bytes = 0 ;(bytes = is.read(buffer)) != -1; )
{
os.write(buffer, 0, bytes);
}
os.flush();
}finally{
if(is != null)
{
is.close();
}
}
}
}
コメント