HttpURLConnection을 이용하여 요청을 처리하는데, 이 URL이 http -> https 나 https -> http로 리다이렉션 되는 경우 넘겨받는 InputStream에 원하는 결과가 들어있지 않다.
다음은 http - https 간의 리다이렉션을 처리하여 InputStream을 넘겨주는 코드이다.
private InputStream openConnectionCheckRedirects(URLConnection c) throws IOException
{
boolean redir;
int redirects = 0;
InputStream in = null;
do
{
if (c instanceof HttpURLConnection)
{
((HttpURLConnection) c).setInstanceFollowRedirects(false);
}
// We want to open the input stream before getting headers
// because getHeaderField() et al swallow IOExceptions.
in = c.getInputStream();
redir = false;
if (c instanceof HttpURLConnection)
{
HttpURLConnection http = (HttpURLConnection) c;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 307 && stat != 306 &&
stat != HttpURLConnection.HTTP_NOT_MODIFIED)
{
URL base = http.getURL();
String loc = http.getHeaderField("Location");
URL target = null;
if (loc != null)
{
target = new URL(base, loc);
}
http.disconnect();
// Redirection should be allowed only for HTTP and HTTPS
// and should be limited to 5 redirections at most.
if (target == null || !(target.getProtocol().equals("http")
|| target.getProtocol().equals("https"))
|| redirects >= 5)
{
throw new SecurityException("illegal URL redirect");
}
redir = true;
c = target.openConnection();
redirects++;
}
}
}
while (redir);
return in;
}
'Java' 카테고리의 다른 글
| valueOf() 와 parseInt() (0) | 2013.03.09 |
|---|---|
| Google Collections (0) | 2010.01.20 |
| OSGi, 번들, 서비스 (0) | 2009.12.11 |