Example usage for java.net HttpURLConnection HTTP_MOVED_PERM

List of usage examples for java.net HttpURLConnection HTTP_MOVED_PERM

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_MOVED_PERM.

Prototype

int HTTP_MOVED_PERM

To view the source code for java.net HttpURLConnection HTTP_MOVED_PERM.

Click Source Link

Document

HTTP Status-Code 301: Moved Permanently.

Usage

From source file:com.connectsdk.service.AirPlayService.java

@Override
public void displayImage(final String url, String mimeType, String title, String description, String iconSrc,
        final LaunchListener listener) {
    Util.runInBackground(new Runnable() {

        @Override/*from   www.j a v  a 2  s  . c o  m*/
        public void run() {
            ResponseListener<Object> responseListener = new ResponseListener<Object>() {

                @Override
                public void onSuccess(Object response) {
                    LaunchSession launchSession = new LaunchSession();
                    launchSession.setService(AirPlayService.this);
                    launchSession.setSessionType(LaunchSessionType.Media);

                    Util.postSuccess(listener, new MediaLaunchObject(launchSession, AirPlayService.this));
                }

                @Override
                public void onError(ServiceCommandError error) {
                    Util.postError(listener, error);
                }
            };

            String uri = getRequestURL("photo");
            byte[] payload = null;

            try {
                URL imagePath = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) imagePath.openConnection();
                connection.setInstanceFollowRedirects(true);
                connection.setDoInput(true);
                connection.connect();

                int responseCode = connection.getResponseCode();
                boolean redirect = (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                        || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                        || responseCode == HttpURLConnection.HTTP_SEE_OTHER);

                if (redirect) {
                    String newPath = connection.getHeaderField("Location");
                    URL newImagePath = new URL(newPath);
                    connection = (HttpURLConnection) newImagePath.openConnection();
                    connection.setInstanceFollowRedirects(true);
                    connection.setDoInput(true);
                    connection.connect();
                }

                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                payload = stream.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(
                    AirPlayService.this, uri, payload, responseListener);
            request.setHttpMethod(ServiceCommand.TYPE_PUT);
            request.send();
        }
    });
}

From source file:org.sakaiproject.commons.tool.entityprovider.CommonsEntityProvider.java

@EntityCustomAction(action = "getUrlMarkup", viewKey = EntityView.VIEW_LIST)
public ActionReturn getUrlMarkup(OutputStream outputStream, EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String urlString = (String) params.get("url");

    if (StringUtils.isBlank(urlString)) {
        throw new EntityException("No url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
    }//w  ww  .  ja va2 s  .co  m

    try {
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL url = new URL(urlString);
        URLConnection c = url.openConnection();

        if (c instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) c;
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            String contentEncoding = conn.getContentEncoding();
            String contentType = conn.getContentType();
            int responseCode = conn.getResponseCode();
            log.debug("Response code: {}", responseCode);

            int redirectCounter = 1;
            while ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || responseCode == HttpURLConnection.HTTP_SEE_OTHER) && redirectCounter < 20) {
                String newUri = conn.getHeaderField("Location");
                log.debug("{}. New URI: {}", responseCode, newUri);
                String cookies = conn.getHeaderField("Set-Cookie");
                url = new URL(newUri);
                c = url.openConnection();
                conn = (HttpURLConnection) c;
                conn.setInstanceFollowRedirects(false);
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.setRequestProperty("Cookie", cookies);
                conn.connect();
                contentEncoding = conn.getContentEncoding();
                contentType = conn.getContentType();
                responseCode = conn.getResponseCode();
                log.debug("Redirect counter: {}", redirectCounter);
                log.debug("Response code: {}", responseCode);
                redirectCounter += 1;
            }

            if (contentType != null
                    && (contentType.startsWith("text/html") || contentType.startsWith("application/xhtml+xml")
                            || contentType.startsWith("application/xml"))) {
                String mimeType = contentType.split(";")[0].trim();
                log.debug("mimeType: {}", mimeType);
                log.debug("encoding: {}", contentEncoding);

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

                String line = null;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                }

                return new ActionReturn(contentEncoding, mimeType, outputStream);
            } else {
                log.debug("Invalid content type {}. Throwing bad request ...", contentType);
                throw new EntityException("Url content type not supported", "",
                        HttpServletResponse.SC_BAD_REQUEST);
            }
        } else {
            throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (MalformedURLException mue) {
        throw new EntityException("Invalid url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
    } catch (IOException ioe) {
        throw new EntityException("Failed to download url contents", "",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:net.caseif.flint.steel.lib.net.gravitydevelopment.updater.Updater.java

private URL followRedirects(String location) throws IOException {
    URL resourceUrl, base, next;/*from w w  w. j a  v a  2 s  .c o m*/
    HttpURLConnection conn;
    String redLoc;
    while (true) {
        resourceUrl = new URL(location);
        conn = (HttpURLConnection) resourceUrl.openConnection();

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0...");

        switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
            redLoc = conn.getHeaderField("Location");
            base = new URL(location);
            next = new URL(base, redLoc); // Deal with relative URLs
            location = next.toExternalForm();
            continue;
        }
        break;
    }
    return conn.getURL();
}

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

private Result getResourceImpl(IRtXMASessionClient session, URL url, long modifiedSince, String etag)
        throws CommunicationException {

    /* locals ---------------------------------- */
    Result result = new Result();
    int code = 0;
    HttpURLConnection conn;/*from ww  w  .j a  va  2 s.c  om*/
    /* locals ---------------------------------- */

    try {
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }
        sendCookies(session, url, conn);
        if (etag != null) {
            conn.setRequestProperty("If-None-Match", etag); //$NON-NLS-1$
        }

        String strUrl = url.toExternalForm();
        if (url.getQuery() == null && (strUrl.endsWith(".jar") || strUrl.endsWith(".xml"))) {
            conn.setRequestProperty(Statics.HTTP_CACHE_CONTROL, Statics.HTTP_MAX_AGE + "=0"); //$NON-NLS-1$
        }

        if (modifiedSince > 0) {
            // see sun bugid: 4397096
            // if HTTP_Util library is used, the original method may also be used.
            // conn.setIfModifiedSince(modifiedSince);
            conn.setRequestProperty(Statics.strIfModifiedSince, HTTPTransport.httpDate(modifiedSince));
        }
        conn.setRequestProperty(Statics.HTTP_ACCEPT, "*/*"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME);

    } catch (IOException exc) {
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' form server:", exc); //$NON-NLS-1$
        throw new ConnectException("error loading '" + url.toString() + "' form server:", exc);
    }

    try {
        code = conn.getResponseCode();
        if (code == HttpURLConnection.HTTP_NOT_MODIFIED) {
            result.contentLength_ = 0;
            result.lastModified_ = conn.getLastModified();
            if (result.lastModified_ <= 0) {
                result.lastModified_ = modifiedSince;
            }
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            if (result.etag_ == null) {
                result.etag_ = etag;
            }
            log_.log(LogLevel.FINE, "resource not modified: {0}", url.toExternalForm()); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_OK) {
            result.contentLength_ = conn.getContentLength();
            result.lastModified_ = conn.getLastModified();
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            result.transformations_ = conn.getHeaderField(Statics.TRANSFORM_HEADER);

            result.setBuffer(this.readOutput(conn));

            if (result.contentLength_ < 0) {
                result.contentLength_ = result.buffer_.length;
            }
        } else if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM) {
            String location = conn.getHeaderField(Statics.HTTP_LOCATION);
            throw new RedirectException("redirect received from " + url.toString() + " to " + location, code,
                    location);
        } else {
            if (code < 500)
                throw new ConnectException("error loading '" + url.toString() + "' from the server:", code);
            else
                throw new ServerException("error loading '" + url.toString() + "' from the server:", code);
        }
        readCookies(session, url, conn);
    } catch (RedirectException re) {
        throw re;
    } catch (CommunicationException ce) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ce); //$NON-NLS-1$
        throw ce;
    } catch (Exception ex) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ex); //$NON-NLS-1$
        if (code < 500)
            throw new ConnectException("error loading '" + url.toString() + "' from the server:", ex);
        else
            throw new ServerException("error loading '" + url.toString() + "' from the server:", ex);
    }

    return result;
}

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

private byte[] callServerEventImpl(IRtXMASessionClient session, URL url, byte[] input, boolean handleRedirect)
        throws CommunicationException {
    OutputStream serverIn;//from  w w  w.j ava 2s .  c om
    int code = 0;
    HttpURLConnection conn;
    byte[] buffer = null;

    try {
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }
        conn.setDoOutput(true);
        conn.setRequestMethod("POST"); //$NON-NLS-1$
        sendCookies(session, url, conn);
        conn.setRequestProperty(Statics.HTTP_CONTENT_TYPE, "application/octet-stream"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_ACCEPT, "application/octet-stream"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME);
        serverIn = conn.getOutputStream();
    } catch (IOException exc) {
        log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", exc); //$NON-NLS-1$
        throw new ConnectException("error calling '" + url.toString() + "' at the server:", exc);
    }

    try {
        serverIn.write(input);
        serverIn.close();
        code = conn.getResponseCode();

        // if requested, we allow redirect also on POST requests, therewith violating RFC 2616 section 10.3!
        if (handleRedirect && code == HttpURLConnection.HTTP_MOVED_TEMP
                || code == HttpURLConnection.HTTP_MOVED_PERM) {
            String location = conn.getHeaderField(Statics.HTTP_LOCATION);
            throw new RedirectException("redirect received from " + url.toString() + " to " + location, code,
                    location);
        }

        buffer = this.readOutput(conn);
        readCookies(session, url, conn);
        return buffer;
    } catch (RedirectException re) {
        throw re;
    } catch (CommunicationException ce) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", ce); //$NON-NLS-1$
        throw ce;
    } catch (Exception ex) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", ex); //$NON-NLS-1$
        if (code < 500)
            throw new ConnectException("error calling '" + url.toString() + "' at the server:", ex);
        else
            throw new ServerException("error calling '" + url.toString() + "' at the server:", ex);
    }
}

From source file:com.day.cq.wcm.foundation.impl.Rewriter.java

/**
 * Process a page.//  w  ww.j a v a  2s  . c  o m
 */
public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {
        targetURL = new URI(target);
    } catch (URISyntaxException e) {
        IOException ioe = new IOException("Bad URI syntax: " + target);
        ioe.initCause(e);
        throw ioe;
    }
    setHostPrefix(targetURL);

    HttpClient httpClient = new HttpClient();
    HttpState httpState = new HttpState();
    HostConfiguration hostConfig = new HostConfiguration();
    HttpMethodBase httpMethod;

    // define host
    hostConfig.setHost(targetURL.getHost(), targetURL.getPort());

    // create http method
    String method = (String) request.getAttribute("cq.ext.app.method");
    if (method == null) {
        method = request.getMethod();
    }
    method = method.toUpperCase();
    boolean isPost = "POST".equals(method);
    String urlString = targetURL.getPath();
    StringBuffer query = new StringBuffer();
    if (targetURL.getQuery() != null) {
        query.append("?");
        query.append(targetURL.getQuery());
    }
    //------------ GET ---------------
    if ("GET".equals(method)) {
        // add internal props
        Iterator<String> iter = extraParams.keySet().iterator();
        while (iter.hasNext()) {
            String name = iter.next();
            String value = extraParams.get(name);
            if (query.length() == 0) {
                query.append("?");
            } else {
                query.append("&");
            }
            query.append(Text.escape(name));
            query.append("=");
            query.append(Text.escape(value));
        }
        if (passInput) {
            // add request params
            @SuppressWarnings("unchecked")
            Enumeration<String> e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                if (targetParamName.equals(name)) {
                    continue;
                }
                String[] values = request.getParameterValues(name);
                for (int i = 0; i < values.length; i++) {
                    if (query.length() == 0) {
                        query.append("?");
                    } else {
                        query.append("&");
                    }
                    query.append(Text.escape(name));
                    query.append("=");
                    query.append(Text.escape(values[i]));
                }
            }

        }
        httpMethod = new GetMethod(urlString + query);
        //------------ POST ---------------
    } else if ("POST".equals(method)) {
        PostMethod m = new PostMethod(urlString + query);
        httpMethod = m;
        String contentType = request.getContentType();
        boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/");
        if (mp) {
            //------------ MULTPART POST ---------------
            List<Part> parts = new LinkedList<Part>();
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                parts.add(new StringPart(name, value));
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        parts.add(new StringPart(name, values[i]));
                    }
                }
            }
            m.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams()));
        } else {
            //------------ NORMAL POST ---------------
            // add internal props
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                m.addParameter(name, value);
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        m.addParameter(name, values[i]);
                    }
                }
            }
        }
    } else {
        log.error("Unsupported method ''{0}''", method);
        throw new IOException("Unsupported http method " + method);
    }
    log.debug("created http connection for method {0} to {1}", method, urlString + query);

    // add some request headers
    httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent"));
    httpMethod.setFollowRedirects(!isPost);
    httpMethod.getParams().setSoTimeout(soTimeout);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // send request
    httpClient.executeMethod(hostConfig, httpMethod, httpState);
    String contentType = httpMethod.getResponseHeader("Content-Type").getValue();

    log.debug("External app responded: {0}", httpMethod.getStatusLine());
    log.debug("External app contenttype: {0}", contentType);

    // check response code
    int statusCode = httpMethod.getStatusCode();
    if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) {
        PrintWriter writer = response.getWriter();
        writer.println("External application returned status code: " + statusCode);
        return;
    } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
        String location = httpMethod.getResponseHeader("Location").getValue();
        if (location == null) {
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
            return;
        }
        response.sendRedirect(rewriteURL(location, false));
        return;
    }

    // open input stream
    InputStream in = httpMethod.getResponseBodyAsStream();

    // check content type
    if (contentType != null && contentType.startsWith("text/html")) {
        rewriteHtml(in, contentType, response);
    } else {
        // binary mode
        if (contentType != null) {
            response.setContentType(contentType);
        }
        OutputStream outs = response.getOutputStream();

        try {
            byte buf[] = new byte[8192];
            int len;

            while ((len = in.read(buf)) != -1) {
                outs.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java

private String sendRequest(Map<String, String> parameters) {
    URL url = createRequestUrl(parameters);
    HttpURLConnection urlConn;// w w  w .  j a  v  a  2  s.c o m

    try {
        urlConn = (HttpURLConnection) url.openConnection();
        // setup url connection
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setInstanceFollowRedirects(false);
        // add content type
        urlConn.setRequestProperty("Content-Type", CONTENT_TYPE);
        // add cookie information
        if (cookie != null)
            urlConn.setRequestProperty("Cookie", cookie);

        // send request
        urlConn.connect();

        // detect redirect
        int code = urlConn.getResponseCode();
        boolean moved = code == HttpURLConnection.HTTP_MOVED_PERM | code == HttpURLConnection.HTTP_MOVED_TEMP;
        if (moved) {
            String location = urlConn.getHeaderField("Location");
            List<String> headerVals = urlConn.getHeaderFields().get("Set-Cookie");
            for (String val : headerVals) {
                if (val.startsWith(COOKIE))
                    cookie = val;
            }
            url = createRedirectUrl(location);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestProperty("Cookie", cookie);
        }

        // read response
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null)
            response.append(line).append("\n");
        input.close();

        if (isLogDebugEnabled())
            logDebug("Response: " + response);

        return response.toString();
    } catch (IOException e) {
        logError("Sending request to Wimba Classroom failed. Request: " + url.toString(), e);
        return "";
    }
}

From source file:io.sloeber.core.managers.Manager.java

/**
 * copy a url locally taking into account redirections
 *
 * @param url//from w  w w .ja v a2 s  .c  o m
 * @param localFile
 */
@SuppressWarnings("nls")
private static void myCopy(URL url, File localFile) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        conn.addRequestProperty("User-Agent", "Mozilla");
        conn.addRequestProperty("Referer", "google.com");

        // normally, 3xx is redirect
        int status = conn.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)

                Files.copy(new URL(conn.getHeaderField("Location")).openStream(), localFile.toPath(),
                        REPLACE_EXISTING);
        } else {
            Files.copy(url.openStream(), localFile.toPath(), REPLACE_EXISTING);
        }

    } catch (Exception e) {
        Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to download url " + url, e));
    }
}

From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java

private String getIconUrlWithHttpRedirect(String imageUrl) throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    int statusCode = conn.getResponseCode();

    if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_SEE_OTHER) {
        return conn.getHeaderField("Location");
    } else {/*  w w  w . ja va  2s  . c  o  m*/
        return imageUrl;
    }
}

From source file:com.techventus.server.voice.Voice.java

/**
 * HTTP GET request for a given URL String.
 * /*from  w  ww .j av a 2s .c o  m*/
 * @param urlString
 *            the url string
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
String get(String urlString) throws IOException {
    URL url = new URL(urlString);
    //+ "?auth=" + URLEncoder.encode(authToken, enc));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);
    conn.setInstanceFollowRedirects(false); // will follow redirects of same protocol http to http, but does not follow from http to https for example if set to true

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(urlString + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
            || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
            || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == 307) {
        redirectCounter++;
        if (redirectCounter > MAX_REDIRECTS) {
            redirectCounter = 0;
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Too manny redirects. exiting.");
        }
        String location = conn.getHeaderField("Location");
        if (location != null && !location.equals("")) {
            System.out.println(urlString + " - " + responseCode + " - new URL: " + location);
            return get(location);
        } else {
            throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                    + ") : Received moved answer but no Location. exiting.");
        }
    } else {
        is = conn.getErrorStream();
    }
    redirectCounter = 0;

    if (is == null) {
        throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode
                + ") : InputStream was null : exiting.");
    }

    String result = "";
    try {
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line + "\n\r");
        }
        rd.close();
        result = sb.toString();
    } catch (Exception e) {
        throw new IOException(urlString + " - " + conn.getResponseMessage() + "(" + responseCode + ") - "
                + e.getLocalizedMessage());
    }
    return result;
}