Example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY

List of usage examples for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY.

Prototype

int SC_MOVED_TEMPORARILY

To view the source code for org.apache.commons.httpclient HttpStatus SC_MOVED_TEMPORARILY.

Click Source Link

Document

<tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945)

Usage

From source file:com.baidu.qa.service.test.client.HttpReqImpl.java

/**
 * use httpclient/*from  www .j a v  a 2 s . co m*/
 * @param file
 * @param config
 * @param vargen
 * @return
 */
public Object requestHttpByHttpClient(File file, Config config, VariableGenerator vargen) {
    FileCharsetDetector det = new FileCharsetDetector();
    try {
        String oldcharset = det.guestFileEncoding(file);
        if (oldcharset.equalsIgnoreCase("UTF-8") == false)
            FileUtil.transferFile(file, oldcharset, "UTF-8");
    } catch (Exception ex) {
        log.error("[change expect file charset error]:" + ex);
    }

    Map<String, String> datalist = FileUtil.getMapFromFile(file, "=");
    if (datalist.size() <= 1) {
        return true;
    }
    if (!datalist.containsKey(Constant.KW_ITEST_HOST) && !datalist.containsKey(Constant.KW_ITEST_URL)) {
        log.error("[wrong file]:" + file.getName() + " hasn't Url");
        return null;
    }
    if (datalist.containsKey(Constant.KW_ITEST_HOST)) {
        this.url = datalist.get(Constant.KW_ITEST_HOST);
        this.hashost = true;
        datalist.remove(Constant.KW_ITEST_HOST);
    } else {
        String action = datalist.get(Constant.KW_ITEST_URL);
        if (config.getHost().lastIndexOf("/") == config.getHost().length() - 1 && action.indexOf("/") == 0) {
            action = action.substring(1);
        }
        this.url = config.getHost() + action;
        datalist.remove("itest_url");

    }
    if (datalist.containsKey(Constant.KW_ITEST_EXPECT)) {
        this.itest_expect = datalist.get(Constant.KW_ITEST_EXPECT);
        datalist.remove(Constant.KW_ITEST_EXPECT);
    }
    if (datalist.containsKey(Constant.KW_ITEST_JSON)) {
        this.itest_expect_json = datalist.get(Constant.KW_ITEST_JSON);
        datalist.remove(Constant.KW_ITEST_JSON);
    }
    parammap = datalist;
    this.config = config;

    //HttpClient
    HttpClient httpClient = new HttpClient();
    //
    httpClient.setConnectionTimeout(30000);
    httpClient.setTimeout(30000);
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    PostMethod postMethod = new PostMethod(url);

    if (hashost == false) {
        //cookie copy
        if (config.getVariable() != null
                && config.getVariable().containsKey(Constant.V_CONFIG_VARIABLE_COOKIE)) {

            postMethod.addRequestHeader(Constant.V_CONFIG_VARIABLE_COOKIE,
                    (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE));
            log.info("[HTTP Request Cookie]"
                    + (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE));
        }
    }

    //??keysparams??body??key=value?
    if (parammap.size() == 1 && (parammap.containsKey("params") || parammap.containsKey("Params"))) {
        String key = "";
        if (parammap.containsKey("params")) {
            key = "params";
        } else if (parammap.containsKey("Params")) {
            key = "Params";
        }
        postMethod.setRequestHeader("Content-Type", "text/json;charset=utf-8");
        postMethod.setRequestBody(parammap.get(key).toString());
    } else {
        NameValuePair[] data = new NameValuePair[parammap.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : parammap.entrySet()) {
            log.info("[HTTP post params]" + (String) entry.getKey() + ":" + (String) entry.getValue() + ";");
            if (entry.getValue().toString().contains("###")) {

            } else {
                data[i] = new NameValuePair((String) entry.getKey(), (String) entry.getValue());
            }
            i++;
        }
        // ?postMethod
        postMethod.setRequestBody(data);
    }

    Assert.assertNotNull("get request error,check the input file", postMethod);

    String response = "";
    // postMethod
    try {
        int statusCode = httpClient.executeMethod(postMethod);
        // HttpClient????POSTPUT???
        // 301302
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                log.info("The page was redirected to:" + location);
            } else {
                log.info("Location field value is null.");
            }
        }

        //? 
        byte[] responseBody = postMethod.getResponseBody();
        if (responseBody == null) {
            log.error("[HTTP response is null]:please check login or servlet");
            return "";
        }
        //?utf-8
        response = new String(responseBody, "UTF-8");
        //?
        log.info("[The Post Request's Response][" + url + "]" + response);

        // responseoutput
        File resfile = FileUtil.rewriteFile(file.getParentFile().getParent() + Constant.FILENAME_OUTPUT,
                file.getName().substring(0, file.getName().indexOf(".")) + ".response", response);

        // 
        vargen.processProps(resfile);
        //??
        if (this.itest_expect != null && this.itest_expect.trim().length() != 0) {
            Assert.assertTrue(
                    "response different with expect:[expect]:" + this.itest_expect + "[actual]:" + response,
                    response.contains(this.itest_expect));
        }
        //                  if(this.itest_expect_json!=null&&this.itest_expect_json.trim().length()!=0){
        //                     VerifyJsonTypeResponseImpl.verifyResponseWithJson(this.itest_expect_json,response);
        //
        //                  }

    } catch (HttpException e) {
        //?????
        log.error("Please check your provided http address!" + e.getMessage());

    } catch (IOException e) {
        //?
        log.error(e.getMessage());
    } catch (Exception e) {
        log.error("[HTTP REQUEST ERROR]:", e);
        //case fail
        throw new RuntimeException("HTTP REQUEST ERROR:" + e.getMessage());
    } finally {
        //
        postMethod.releaseConnection();
    }
    return response;
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

public HttpInputStream sendPut(String href, byte[] buf, String contentType, String etag,
        Collection<Pair<String, String>> headers) throws IOException {
    boolean done = false;
    PutMethod put = null;//from  ww w .  ja  v  a2 s. c  o m
    while (!done) {
        put = new PutMethod(mBaseUrl + href);
        put.setRequestEntity(new ByteArrayRequestEntity(buf, contentType));
        if (mDebugEnabled && contentType.startsWith("text"))
            ZimbraLog.dav.debug("PUT payload: \n" + new String(buf, "UTF-8"));
        if (etag != null)
            put.setRequestHeader(DavProtocol.HEADER_IF_MATCH, etag);
        if (headers != null)
            for (Pair<String, String> h : headers)
                put.addRequestHeader(h.getFirst(), h.getSecond());
        executeMethod(put, Depth.zero);
        int ret = put.getStatusCode();
        if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header newLocation = put.getResponseHeader("Location");
            if (newLocation != null) {
                href = newLocation.getValue();
                ZimbraLog.dav.debug("redirect to new url = " + href);
                put.releaseConnection();
                continue;
            }
        }
        done = true;
    }
    return new HttpInputStream(put);
}

From source file:com.buzzdavidson.spork.client.OWAClient.java

/**
 * Perform login to OWA server given configuration parameters and supplied user/password
 *
 * @param userName  user name for login/*from w  w  w. j ava  2  s  . com*/
 * @param password password for login
 * @return true if successfully authenticated
 */
public boolean login(String userName, String password) {
    /**
     * Set NT credentials on client
     */
    Credentials cred;
    cred = new NTCredentials(userName, password, authHost, authDomain);
    client.getState().setCredentials(new AuthScope(authHost, AuthScope.ANY_PORT), cred);

    String authUrl = getBaseUrl() + loginPath;
    boolean retval = false;
    logger.info(String.format("Logging in to OWA using username [%s] at URL [%s] ", userName, authUrl));
    PostMethod post = new PostMethod(authUrl);
    post.setRequestHeader(PARAM_CONTENT_TYPE, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE);
    post.addParameter(PARAM_DEST, getBaseUrl() + docBasePath);
    post.addParameter(PARAM_UNAME, userName);
    post.addParameter(PARAM_PWD, password);
    post.addParameter(PARAM_FLAGS,
            publicComputer ? OWA_FLAG_VALUE_PUBLIC.toString() : OWA_FLAG_VALUE_PRIVATE.toString());

    int status = 0;
    try {
        status = client.executeMethod(post);
        if (logger.isDebugEnabled()) {
            logger.debug("Post returned status code " + status);
        }
    } catch (Exception ex) {
        logger.error("Got error posting to login url", ex);
    }

    if (status == HttpStatus.SC_OK) {
        // We shouldn't see this in normal operation... Evaluate whether this actually ever occurs.
        logger.info("Login succeeded (no redirect specified)");
        retval = true;
    } else if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
        // We typically receive a redirect upon successful authentication; the target url is the user's inbox
        Header locationHeader = post.getResponseHeader(HEADER_LOCATION);
        if (locationHeader != null) {
            String mbxRoot = getMailboxRoot(locationHeader.getValue());
            if (mbxRoot == null || mbxRoot.length() < 1) {
                logger.info("Login failed - Check configuration and credentials.");
                retval = false;
            } else {
                owaRootUrl = mbxRoot;
                inboxAddress = owaRootUrl + "/" + FOLDER_NAME_INBOX; // TODO is this sufficient?
                logger.info("Login succeeded, redirect specified (redirecting to " + owaRootUrl + ")");
                retval = true;
            }
        }
    } else {
        logger.error("Login failed with error code " + status);
    }
    return retval;
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

protected HttpMethod executeFollowRedirect(DavRequest req) throws IOException {
    HttpMethod method = null;/*from   w ww .  j ava 2 s  .c o  m*/
    boolean done = false;
    while (!done) {
        method = execute(req);
        int ret = method.getStatusCode();
        if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header newLocation = method.getResponseHeader("Location");
            if (newLocation != null) {
                String uri = newLocation.getValue();
                ZimbraLog.dav.debug("redirect to new url = " + uri);
                method.releaseConnection();
                req.setRedirectUrl(uri);
                continue;
            }
        }
        done = true;
    }
    return method;
}

From source file:com.mirth.connect.client.core.UpdateClient.java

public void registerUser(User user) throws ClientException {
    HttpClientParams httpClientParams = new HttpClientParams();
    HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
    httpClientParams.setSoTimeout(10 * 1000);
    httpConnectionManager.getParams().setConnectionTimeout(10 * 1000);
    httpConnectionManager.getParams().setSoTimeout(10 * 1000);
    HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager);

    PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_REGISTRATION);
    NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()),
            new NameValuePair("version", client.getVersion()),
            new NameValuePair("user", serializer.toXML(user)) };
    post.setRequestBody(params);// www.  j a  v a  2  s .  c om

    try {
        int statusCode = httpClient.executeMethod(post);

        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + post.getStatusLine());
        }
    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

/** 
 * POST//w  w  w  . j av a  2 s .c o m
 * 
 * Posts the parametersBody
 * @throws RailsAppException 
 */
protected byte[] post(NameValuePair[] parametersBody, Map<String, Object[]> files)
        throws HttpException, IOException, RailsAppException {
    // Response body from the web server
    byte[] responseBody = null;
    statusCode = -1;

    List<File> tempFiles = null;

    HttpClient client = preparedClient();

    // Create a method instance.
    PostMethod method = new PostMethod(requestURL.toString());
    HttpMethod _method = (HttpMethod) method;

    String action = "POST action request URL: " + requestURL.toString();
    if (ajax) {
        log.debug("Ajax " + action);
        _method.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
        _method.setRequestHeader("ACCEPT", "text/javascript, text/html, application/xml, text/xml, */*");
        _method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    } else
        log.debug(action);

    // finalize method
    method = (PostMethod) prepareMethodHeaders(_method);

    if (files != null && files.size() > 0) {

        tempFiles = new ArrayList<File>();
        createMultipartRequest(parametersBody, files, method, tempFiles);

    } else {
        // Array of parameters may not be null, so init empty NameValuePair[]
        if (parametersBody == null) {
            parametersBody = new NameValuePair[0];
        }
        method.setRequestBody(parametersBody);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
    }

    try {
        // Execute the method.
        statusCode = client.executeMethod(method);

        if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

            // get Location
            String location = ((Header) method.getResponseHeader("Location")).getValue();
            requestURL = new URL(location);
            log.debug("POST status code: " + method.getStatusLine());
            log.debug("Redirect to location: " + location);

            // server may add another cookie before redirect..
            cookies = client.getState().getCookies();

            // Note that this GET overwrites the previous POST method,
            // so it should set statusCode and cookies correctly.
            responseBody = get();

        } else {
            // the original POST method was OK, pass
            // No more redirects! Response should be 200 OK
            if (statusCode != HttpStatus.SC_OK) {
                String errorMessage = "Method failed: " + method.getStatusLine();
                log.error(errorMessage);
                throw new RailsAppException(errorMessage, new String(method.getResponseBody()));

            } else {
                log.debug("POST status code: " + method.getStatusLine());
            }

            // Read the response body.
            responseBody = method.getResponseBody();

            // Keep the headers for future usage (render or resource phase)
            configureHeader(method.getResponseHeaders());

            // Get session cookies
            cookies = client.getState().getCookies();
        }

    } finally {
        // Release the connection
        method.releaseConnection();

        // Delete temp files
        deleteFiles(tempFiles);
    }

    return responseBody;
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();/*from   w ww. j  a v a 2  s  .  c  o m*/

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Authenticate the client http state so that the colony requests can be made.
 *
 * @param baseURL URL requested for colony
 * @param client  HttpClient instance//from w  ww  .j a va 2 s. co m
 *
 * @return true if authentication succeeded.
 *
 * @throws com.dtolabs.client.utils.HttpClientException
 *
 */
public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException {
    final HttpState state = client.getState();
    if (hasSessionCookie(baseURL, state, basePath)) {
        return true;
    }
    final byte[] buffer = new byte[1024];

    boolean doPostLogin = false;
    boolean isLoginFormContent = false;
    logger.debug("No session found, must login...");
    try {
        final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                basePath + getInitialPath());

        //load welcome page, which should forward to form based logon page.
        final GetMethod get = new GetMethod(newUrl.toExternalForm());
        get.setDoAuthentication(false);
        get.setFollowRedirects(false);
        logger.debug("Requesting: " + newUrl);
        int res = client.executeMethod(get);
        logger.debug("Result is: " + res);

        /*
          Tomcat container auth behaves differently than Jetty.  Tomcat will respond 200 OK and include the login form
          when auth is required, as well as on auth failure, it will also require complete GET of original URL after
          successful auth.
          Jetty will redirect to login page when auth is required, and will redirect to error page on failure.
         */

        String body = get.getResponseBodyAsString();
        if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM)
                && body.contains(JAVA_PASS_PARAM)) {
            isLoginFormContent = true;
        }
        get.releaseConnection();

        if ((res == HttpStatus.SC_UNAUTHORIZED)) {
            if (get.getResponseHeader("WWW-Authenticate") != null
                    && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) {
                logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication");
                final BasicAuthenticator auth = new BasicAuthenticator(username, password);
                return auth.authenticate(baseURL, client);
            } else {
                throw new HttpClientException(
                        "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session");
            }

        }
        //should now have the proper session cookie
        if (!hasSessionCookie(baseURL, state, basePath)) {
            throw new HttpClientException("Unable to get a session from URL : " + newUrl);
        }
        if (res == HttpStatus.SC_OK && isLoginFormContent) {
            doPostLogin = true;
        } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            Header locHeader = get.getResponseHeader("Location");
            if (locHeader == null) {
                throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
            }
            String location = locHeader.getValue();
            if (!isValidLoginRedirect(get)) {
                //unexpected response
                throw new HttpClientException("Unexpected redirection when getting session: " + location);
            }
            logger.debug("Follow redirect: " + res + ": " + location);

            final GetMethod redir = new GetMethod(location);
            redir.setFollowRedirects(true);
            res = client.executeMethod(redir);
            InputStream ins = redir.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            redir.releaseConnection();

            if (res != HttpStatus.SC_OK) {
                throw new HttpClientException("Login page status was not OK: " + res);
            }
            logger.debug("Result: " + res);

            doPostLogin = true;
        } else if (res != HttpStatus.SC_OK) {
            //if request to welcome page was OK, we figure that the session is already set
            throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get);
        }
        if (doPostLogin) {
            //now post login
            final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                    basePath + JAVA_AUTH_PATH);

            final PostMethod login = new PostMethod(loginUrl.toExternalForm());
            login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()),
                    new NameValuePair(JAVA_PASS_PARAM, getPassword()) });

            login.setFollowRedirects(false);
            logger.debug("Post login info to URL: " + loginUrl);

            res = client.executeMethod(login);

            final InputStream ins = login.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            login.releaseConnection();

            Header locHeader = login.getResponseHeader("Location");
            String location = null != locHeader ? locHeader.getValue() : null;
            if (isLoginError(login)) {
                logger.error("Form-based auth failed");
                return false;
            } else if (null != location && !location.equals(newUrl.toExternalForm())) {

                logger.warn("Form-based auth succeeded, but last URL was unexpected");
            }
            if (isFollowLoginRedirect()
                    && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                            || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) {

                if (location == null) {
                    throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
                }
                final GetMethod get2 = new GetMethod(location);
                //                    logger.debug("Result: " + res + ": " + location + ", following redirect");
                res = client.executeMethod(get2);
            } else if (res != HttpStatus.SC_OK) {
                throw new HttpClientException(
                        "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString());
            }
            logger.debug("Result: " + res);
        }
    } catch (MalformedURLException e) {
        throw new HttpClientException("Bad URL", e);
    } catch (HttpException e) {
        throw new HttpClientException("HTTP Error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new HttpClientException(
                "Error occurred while trying to authenticate to server: " + e.getMessage(), e);
    }

    return true;
}

From source file:com.mirth.connect.client.core.UpdateClient.java

private List<UpdateInfo> getUpdatesFromUri(ServerInfo serverInfo) throws Exception {
    HttpClientParams httpClientParams = new HttpClientParams();
    HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
    httpClientParams.setSoTimeout(10 * 1000);
    httpConnectionManager.getParams().setConnectionTimeout(10 * 1000);
    httpConnectionManager.getParams().setSoTimeout(10 * 1000);
    HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager);

    PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_UPDATES);
    NameValuePair[] params = { new NameValuePair("serverInfo", serializer.toXML(serverInfo)) };
    post.setRequestBody(params);/*from w w  w  .j ava2 s  . c om*/

    try {
        int statusCode = httpClient.executeMethod(post);

        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + post.getStatusLine());
        }

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        StringBuilder result = new StringBuilder();
        String input = new String();

        while ((input = reader.readLine()) != null) {
            result.append(input);
            result.append('\n');
        }

        return (List<UpdateInfo>) serializer.fromXML(result.toString());
    } catch (Exception e) {
        throw e;
    } finally {
        post.releaseConnection();
    }
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Check endpoint url./*from w  w w .j a  v  a2  s.c  o  m*/
 *
 * @param endPointUrl endpoint url
 * @throws IOException on error
 */
protected void checkEndPointUrl(String endPointUrl) throws IOException {
    HttpMethod getMethod = new GetMethod(endPointUrl);
    getMethod.setFollowRedirects(false);
    try {
        int status = DavGatewayHttpClientFacade.executeNoRedirect(httpClient, getMethod);
        if (status == HttpStatus.SC_UNAUTHORIZED) {
            throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
        } else if (status != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw DavGatewayHttpClientFacade.buildHttpException(getMethod);
        }
        // check Location
        Header locationHeader = getMethod.getResponseHeader("Location");
        if (locationHeader == null || !"/ews/services.wsdl".equalsIgnoreCase(locationHeader.getValue())) {
            throw new IOException("Ews endpoint not available at " + getMethod.getURI().toString());
        }
    } finally {
        getMethod.releaseConnection();
    }
}