drcarter의 DevLog


http에 request를 보냈는데.. 서버에서 url주소를 redirect해서 보내주는 경우가 있지요. 그럼 개발자가 입력한 주소로는
요청이 안되는 경우가 생깁니다. 이걸 해결하기위해서는 javaj에서 redirect된 주소로 다시 요청을 해줘야 합니다.
방법은

private InputStream openConnectionCheckRedirects(URLConnection c) throws IOException 
{
   boolean redir;
   int redirects = 0;
   InputStream in = null;
   do 
   {
      if (c instanceof HttpURLConnection) 
      {
         ((HttpURLConnection) c).setInstanceFollowRedirects(false);
      }
      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();
            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;
}

public void makeConnection(URL url){
   URLConnection conn = url.openConnection();
   InputStream is = openConnectionCheckRedirects(conn);

   /* request에 대한 결과 처리 부분*/

   is.close();
}

이런식으로 하면 되겠습니다. 서버에서 제공하는 api가 redirect된 주소로 해서 보내주는 경우가 많기에... 이 방법을 써서 해결하게 되었습니다.