Example usage for org.apache.commons.httpclient HttpClient getParams

List of usage examples for org.apache.commons.httpclient HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getParams.

Prototype

public HttpClientParams getParams() 

Source Link

Usage

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private String postRequest(PostMethod httppost) throws UnsupportedEncodingException {
    HttpClient client = getHttpClient();
    client.getState().setCredentials(AuthScope.ANY, credentials);
    client.getParams().setAuthenticationPreemptive(true);
    String response = null;//from www  . j a  v a  2s  .  c om
    InputStream responseBodyAsStream = null;
    try {
        client.executeMethod(httppost);
        if (httppost.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // 204, no content
            return "";
        }
        responseBodyAsStream = httppost.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            response = IOUtils.toString(responseBodyAsStream, "UTF-8");
        }
        if (httppost.getStatusCode() != HttpStatus.SC_OK && httppost.getStatusCode() != HttpStatus.SC_CREATED) {
            throw new GogsRequestException(httppost.getStatusCode(), "HTTP request error. Status: "
                    + httppost.getStatusCode() + ": " + httppost.getStatusText() + ".\n" + response);
        }
    } catch (HttpException e) {
        throw new GogsRequestException(0, "Communication error: " + e, e);
    } catch (IOException e) {
        throw new GogsRequestException(0, "Communication error: " + e, e);
    } finally {
        httppost.releaseConnection();
        if (responseBodyAsStream != null) {
            IOUtils.closeQuietly(responseBodyAsStream);
        }
    }
    if (response == null) {
        throw new GogsRequestException(0, "HTTP request error");
    }
    return response;

}

From source file:com.delmar.station.service.impl.WFDetailServiceImpl.java

public String updateDcmsFcrDate(EDIResponseInfo edirInfo, String trustFileCode) {

    String resultMessage = "success";
    Date date = new Date();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    String currentDate = sf.format(date);
    try {/*ww w .j  ava 2s  .c  o m*/
        date = sf.parse(edirInfo.getInDate());
        currentDate = sf.format(date);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    try {

        EDIResponseInfo resultEDIResponseInfo = ediResponseInfoService.getEDIRByTrustFileCode(trustFileCode);

        // Booking IDCargoProDcms????bookingID
        if (StringUtil.isNotEmpty(resultEDIResponseInfo.getCsReferenceNo())) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", resultEDIResponseInfo.getCsReferenceNo());
            params.put("fcrDate", currentDate);
            params.put("remark", edirInfo.getResponseDesc());
            HttpClient httpClient = null;
            httpClient.getParams().setAuthenticationPreemptive(true);

            // ?
            Credentials credentials = new UsernamePasswordCredentials("wsuserchina", "ws1sGreat");
            httpClient.getState().setCredentials(AuthScope.ANY, credentials);

            HttpMethod method = buildPostMethod(
                    "https://www.delmarcargo.com/cms/api/bookingservice/updateBookingFcrDate", params);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpException(method.getStatusText());
            }
            String xmlResult = method.getResponseBodyAsString();
            method.releaseConnection();

            //   
            StringReader xmlReader = new StringReader(xmlResult);
            // ?SAX ? InputSource ?? XML   
            InputSource xmlSource = new InputSource(xmlReader);
            // SAXBuilder  
            SAXReader builder = new SAXReader();
            // ?SAXDocument
            Document doc = builder.read(xmlSource);
            // 
            Element root = doc.getRootElement();
            // BODY 
            Element resultStatusCode = root.element("ServiceResponse").element("statusCode");

            // ????
            if ("200".equals(resultStatusCode.getText())) {
                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("1");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);

                ediResponseInfoService.updateTrustFileInfoFCRDate(currentDate, edirInfo.getTrustFileCode());
            } else if ("405".equals(resultStatusCode.getText())) {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();

                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("11");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);
            } else {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();
            }
        } else {
            resultMessage = "Booking IDCargoProDcms?";
        }
    } catch (Exception e) {
        e.printStackTrace();
        resultMessage = "Modify Dcms Fcr Date have Exception";
        return resultMessage;
    }

    return resultMessage;
}

From source file:fr.jayasoft.ivy.url.HttpClientHandler.java

private HttpClient getClient(URL url) {
    HttpClient client = new HttpClient();

    List authPrefs = new ArrayList(2);
    authPrefs.add(AuthPolicy.DIGEST);/*w  ww  .  j av a 2  s .  c o  m*/
    authPrefs.add(AuthPolicy.BASIC);
    // Exclude the NTLM authentication scheme because it is not supported by this class
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    if (useProxy()) {
        client.getHostConfiguration().setProxy(_proxyHost, _proxyPort);
        if (useProxyAuthentication()) {
            client.getState().setProxyCredentials(_proxyRealm, _proxyHost,
                    new UsernamePasswordCredentials(_proxyUserName, _proxyPasswd));
        }
    }
    Credentials c = getCredentials(url);
    if (c != null) {
        Message.debug("found credentials for " + url + ": " + c);
        client.getState().setCredentials(c.getRealm(), c.getHost(),
                new UsernamePasswordCredentials(c.getUserName(), c.getPasswd()));
    }
    return client;
}

From source file:edu.unc.lib.dl.admin.controller.AbstractSwordController.java

public String updateDatastream(String pid, String datastream, HttpServletRequest request,
        HttpServletResponse response) {/*from ww w .j a v  a  2s  .  c o m*/
    String responseString = null;
    String dataUrl = swordUrl + "object/" + pid;
    if (datastream != null)
        dataUrl += "/" + datastream;

    Abdera abdera = new Abdera();
    Entry entry = abdera.newEntry();
    Parser parser = abdera.getParser();
    Document<FOMExtensibleElement> doc;
    HttpClient client;
    PutMethod method;

    ParserOptions parserOptions = parser.getDefaultParserOptions();
    parserOptions.setCharset(request.getCharacterEncoding());

    try {

        doc = parser.parse(request.getInputStream(), parserOptions);
        entry.addExtension(doc.getRoot());

        client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
        client.getParams().setAuthenticationPreemptive(true);
        method = new PutMethod(dataUrl);
        // Pass the users groups along with the request
        method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());

        Header header = new Header("Content-Type", "application/atom+xml");
        method.setRequestHeader(header);
        StringWriter stringWriter = new StringWriter(2048);
        StringRequestEntity requestEntity;
        entry.writeTo(stringWriter);
        requestEntity = new StringRequestEntity(stringWriter.toString(), "application/atom+xml", "UTF-8");
        method.setRequestEntity(requestEntity);
    } catch (UnsupportedEncodingException e) {
        log.error("Encoding not supported", e);
        return null;
    } catch (IOException e) {
        log.error("IOException while writing entry", e);
        return null;
    }

    try {
        client.executeMethod(method);
        response.setStatus(method.getStatusCode());
        if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // success
            return "";
        } else if (method.getStatusCode() >= 400 && method.getStatusCode() <= 500) {
            if (method.getStatusCode() == 500)
                log.warn("Failed to upload " + datastream + " " + method.getURI().getURI());
            // probably a validation problem
            responseString = method.getResponseBodyAsString();
            return responseString;
        } else {
            response.setStatus(500);
            throw new Exception("Failure to update fedora content due to response of: "
                    + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return responseString;
}

From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java

@Override
public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url");
    String username = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
        LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false)
                + " to " + urlString);
    }//from   ww  w. ja  v a  2  s . co  m
    int retries = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    RequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

        post.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        if (!(username.equals(""))) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating using basic auth");
            }
            URL url = new URL(urlString);
            httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null),
                    new UsernamePasswordCredentials(username, password));
            httpClient.getParams().setAuthenticationPreemptive(true);
            post.setDoAuthentication(true);
        }
        int statusCode = httpClient.executeMethod(post);
        if (statusCode == 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code 200 recieved, event sent OK");
            }
            return true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code " + statusCode + " recieved, event send failed");
            }
            return false;
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:de.hybris.platform.solrfacetsearch.integration.AbstractSolrTest.java

protected void checkStandaloneSolr(final String url) {
    try {/*from  w w w .j  ava 2  s.  c  o m*/
        final HttpClient client = new HttpClient();
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        final GetMethod method = new GetMethod(url);
        method.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        client.executeMethod(method);
    } catch (final HttpException e) {
        Assert.fail("Cannot connect to remote standalone SOLR : " + e.getMessage());
    } catch (final IOException e) {
        Assert.fail("Cannot connect to remote standalone SOLR : " + e.getMessage());
    }
}

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private int getRequestStatus(String path) {
    HttpClient client = getHttpClient();
    client.getState().setCredentials(AuthScope.ANY, credentials);
    GetMethod httpget = new GetMethod(this.baseURL + path);
    client.getParams().setAuthenticationPreemptive(true);
    try {/*from   w  ww  . j a v  a2s  .  c om*/
        client.executeMethod(httpget);
        return httpget.getStatusCode();
    } catch (HttpException e) {
        LOGGER.log(Level.SEVERE, "Communication error", e);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Communication error", e);
    } finally {
        httpget.releaseConnection();
    }
    return -1;
}

From source file:com.zimbra.cs.service.UserServlet.java

private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method)
        throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    try {//from  ww w  . j av a  2s  .  c o  m
        url = method.getURI().toString();
        hostname = method.getURI().getHost();
    } catch (IOException e) {
        log.warn("can't parse target URI", e);
    }

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        HttpState state = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/",
                    null, false));
        }
        client.setState(state);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    if (method instanceof PutMethod) {
        long contentLength = ((PutMethod) method).getRequestEntity().getContentLength();
        if (contentLength > 0) {
            int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);

            method.getParams().setSoTimeout(timeEstimate);
        }
    }

    try {
        int statusCode = HttpClientUtil.executeMethod(client, method);
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null,
                    new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR),
                    new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode,
                            ServiceException.Argument.Type.NUM));

        List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders()));
        headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}

From source file:be.fedict.trust.service.bean.DownloaderMDB.java

private File download(String url) {
    NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig();
    HttpClient httpClient = new HttpClient();
    if (null != networkConfig) {
        httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort());
    }/*from w  ww  .j av  a  2s .c  o  m*/
    HttpClientParams httpClientParams = httpClient.getParams();
    httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20));
    LOG.debug("downloading: " + url);
    GetMethod getMethod = new GetMethod(url);
    getMethod.addRequestHeader("User-Agent", "eID Trust Service Client");
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(getMethod);
    } catch (Exception e) {
        downloadFailed(url);
        throw new RuntimeException();
    }
    if (HttpURLConnection.HTTP_OK != statusCode) {
        LOG.debug("HTTP status code: " + statusCode);
        downloadFailed(url);
        throw new RuntimeException();
    }

    String downloadFilePath;
    File downloadFile = null;
    try {
        downloadFile = File.createTempFile("trust-service-", ".der");
        InputStream downloadInputStream = getMethod.getResponseBodyAsStream();
        OutputStream downloadOutputStream = new FileOutputStream(downloadFile);
        IOUtils.copy(downloadInputStream, downloadOutputStream);
        IOUtils.closeQuietly(downloadInputStream);
        IOUtils.closeQuietly(downloadOutputStream);
        downloadFilePath = downloadFile.getAbsolutePath();
        LOG.debug("temp file: " + downloadFilePath);
    } catch (IOException e) {
        downloadFailed(url);
        if (null != downloadFile) {
            downloadFile.delete();
        }
        throw new RuntimeException(e);
    }
    return downloadFile;
}

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private String getRequest(String path) {
    HttpClient client = getHttpClient();
    client.getState().setCredentials(AuthScope.ANY, credentials);
    GetMethod httpget = new GetMethod(this.baseURL + path);
    client.getParams().setAuthenticationPreemptive(true);
    String response = null;/* w ww . j  a va  2 s .  co m*/
    InputStream responseBodyAsStream = null;
    try {
        client.executeMethod(httpget);
        responseBodyAsStream = httpget.getResponseBodyAsStream();
        response = IOUtils.toString(responseBodyAsStream, "UTF-8");
        if (httpget.getStatusCode() != HttpStatus.SC_OK) {
            throw new GogsRequestException(httpget.getStatusCode(), "HTTP request error. Status: "
                    + httpget.getStatusCode() + ": " + httpget.getStatusText() + ".\n" + response);
        }
    } catch (HttpException e) {
        throw new GogsRequestException(0, "Communication error: " + e, e);
    } catch (IOException e) {
        throw new GogsRequestException(0, "Communication error: " + e, e);
    } finally {
        httpget.releaseConnection();
        if (responseBodyAsStream != null) {
            IOUtils.closeQuietly(responseBodyAsStream);
        }
    }
    if (response == null) {
        throw new GogsRequestException(0,
                "HTTP request error " + httpget.getStatusCode() + ":" + httpget.getStatusText());
    }
    return response;
}