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

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

Introduction

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

Prototype

int SC_OK

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

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:guru.nidi.atlassian.remote.script.RemoteJira.java

Object executeImpl(String command, Object... parameters) throws RpcException {
    PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/jirasoapservice-v2/" + command);
    post.setRequestHeader("Content-Type", "application/json");
    HttpUtils.setAuthHeader(post, username, password);
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from   ww w . j  a  va  2s.c  o m*/
        mapper.writeValue(baos, parameters);
        post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("not ok: " + status + " " + post.getResponseBodyAsString(MAX_RESPONSE_SIZE));
        }
        try {
            ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                    ErrorResponse.class);
            throw new RpcException(errorResponse);
        } catch (JsonParseException e) {
            //ignore
        } catch (JsonMappingException e) {
            //ignore
        }
        try {
            return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                    new TypeReference<HashMap<String, Object>>() {
                    });
        } catch (JsonParseException e) {
            //ignore
        } catch (JsonMappingException e) {
            //ignore
        }
        try {
            return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE),
                    new TypeReference<ArrayList<Object>>() {
                    });
        } catch (JsonParseException e) {
            //ignore
        } catch (JsonMappingException e) {
            //ignore
        }
        return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), String.class);
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return null;
}

From source file:it.geosolutions.geonetwork.op.GNMetadataAdmin.java

private static void gnAdminMetadata(HTTPUtils connection, String baseURL, final Element gnRequest)
        throws GNServerException {

    String serviceURL = baseURL + "/srv/en/metadata.admin";
    gnPut(connection, serviceURL, gnRequest);
    if (connection.getLastHttpStatus() != HttpStatus.SC_OK)
        throw new GNServerException("Error setting metadata privileges in GeoNetwork");
}

From source file:de.bermuda.arquillian.example.ContentTypeProxyServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String localPathInfo = req.getPathInfo() == null ? "" : req.getPathInfo();
    String queryString = req.getQueryString();
    log.info("Setting URL to: " + serviceURL.toExternalForm() + localPathInfo);
    PostMethod post = new PostMethod(serviceURL.toExternalForm() + localPathInfo);
    post.setQueryString(queryString);//w w  w  .  ja  v a2  s.c om

    copyRequestHeaders(req, post);

    copyRequestBody(req, post);

    try {
        int statusCode = client.executeMethod(post);
        if (statusCode != HttpStatus.SC_OK) {
            log.warn("Could not post request to i.Serve: " + statusCode);
        }

        migrateResponseHeader(resp, post);

        copyResponseContent(resp, post);
    } catch (HttpException e) {
        log.error("Catched HTTPException: ", e);
    } catch (IOException e) {
        log.error("Catched IOException: ", e);
    }
}

From source file:cn.newtouch.util.HttpClientUtil.java

/**
 * ?url??post/*from ww w.  j  a  va  2  s . c o m*/
 * 
 * @param url
 * @param paramsStr
 *            ?
 * @param method
 * @return String ?
 */
public static String post(String url, String paramsStr, String method) {

    HttpClient client = new HttpClient();
    HttpMethod httpMethod = new PostMethod(url);
    httpMethod.setQueryString(paramsStr);
    try {
        int returnCode = client.executeMethod(httpMethod);
        if (returnCode == HttpStatus.SC_OK) {
            return httpMethod.getResponseBodyAsString();
        } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
        }
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        httpMethod.releaseConnection();
    }
    return null;
}

From source file:com.owncloud.android.lib.resources.files.StoreMetadataOperation.java

/**
 * @param client Client object/*from w w w. jav  a 2 s  . co  m*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    PostMethod postMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        postMethod = new PostMethod(client.getBaseUri() + METADATA_URL + fileId + JSON_FORMAT);
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        postMethod.setParameter(METADATA, encryptedMetadataJson);

        int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            String response = postMethod.getResponseBodyAsString();

            // Parse the response
            JSONObject respJSON = new JSONObject(response);
            String metadata = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA)
                    .get(NODE_META_DATA);

            result = new RemoteOperationResult(true, postMethod);
            ArrayList<Object> keys = new ArrayList<>();
            keys.add(metadata);
            result.setData(keys);
        } else {
            result = new RemoteOperationResult(false, postMethod);
            client.exhaustResponse(postMethod.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Storing of metadata for folder " + fileId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (postMethod != null)
            postMethod.releaseConnection();
    }
    return result;
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument search(HashMap<String, String> request)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;//from   w  ww .j av  a2  s  .c om
    String urlStr = prepareUrl(request);
    Log.debug("The following search is goint to be executed:" + urlStr);
    // Create a method instance.
    method = new GetMethod(urlStr);

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

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:jenkins.plugins.office365connector.HttpWorker.java

@Override
public void run() {
    int tried = 0;
    boolean success = false;
    HttpClient client = getHttpClient();
    client.getParams().setConnectionManagerTimeout(timeout);
    do {/*from  ww w.jav a  2 s .co m*/
        tried++;
        RequestEntity requestEntity;
        try {
            // uncomment to log what message has been sent
            // log("Posted JSON: %s", data);
            requestEntity = new StringRequestEntity(data, "application/json", StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(logger);
            break;
        }

        PostMethod post = new PostMethod(url);
        try {
            post.setRequestEntity(requestEntity);
            int responseCode = client.executeMethod(post);
            if (responseCode != HttpStatus.SC_OK) {
                String response = post.getResponseBodyAsString();
                log("Posting data to %s may have failed. Webhook responded with status code - %s", url,
                        responseCode);
                log("Message from webhook - %s", response);

            } else {
                success = true;
            }
        } catch (IOException e) {
            log("Failed to post data to webhook - %s", url);
            e.printStackTrace(logger);
        } finally {
            post.releaseConnection();
        }
    } while (tried < RETRIES && !success);

}

From source file:apm.common.utils.HttpTookit.java

/**
 * HTTP POST?HTML//ww w.  java2 s.com
 * 
 * @param url
 *            URL?
 * @param params
 *            ?,?null
 * @param charset
 *            
 * @param pretty
 *            ?
 * @return ?HTML
 */
public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = new PostMethod(url);
    // Http Post?
    if (params != null) {
        HttpMethodParams p = new HttpMethodParams();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            p.setParameter(entry.getKey(), entry.getValue());
        }
        method.setParams(p);
    }
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append(System.getProperty("line.separator"));
                } else {
                    response.append(line);
                }
            }
            reader.close();
        }
    } catch (IOException e) {
        log.error("HTTP Post" + url + "??", e);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}

From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java

public String loadCommitMessage(final String url) {
    final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() {
        public String call() {
            final HttpClient client = new HttpClient();
            final GetMethod getMethod = new GetMethod(url);
            try {
                final int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK)
                    throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")");
                return getMethod.getResponseBodyAsString();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }/*from   www  .  ja v  a  2  s . c o m*/
        }
    });

    ApplicationManager.getApplication().executeOnPooledThread(downloadTask);

    try {
        return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        // ignore
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    if (!downloadTask.isDone()) {
        downloadTask.cancel(true);
        throw new RuntimeException("Connection timed out");
    }

    return "";
}

From source file:it.geosolutions.figis.requester.HTTPUtils.java

/**
* Performs an HTTP GET on the given URL.
* <BR>Basic auth is used if both username and pw are not null.
*
* @param url The URL where to connect to.
* @param username Basic auth credential. No basic auth if null.
* @param pw Basic auth credential. No basic auth if null.
* @return The HTTP response as a String if the HTTP response code was 200 (OK).
* @throws MalformedURLException//from  w w w .  j  av a 2s .  c  o m
*/
public static String get(String url, String username, String pw) throws MalformedURLException {
    GetMethod httpMethod = null;
    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(httpMethod);
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            String response = IOUtils.toString(is);
            if (response.trim().length() == 0) // sometime gs rest fails
            {
                LOGGER.warn("ResponseBody is empty");

                return null;
            } else {
                return response;
            }
        } else {
            LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url);
        }
    } catch (ConnectException e) {
        LOGGER.error("Couldn't connect to [" + url + "]", e);
    } catch (IOException e) {
        LOGGER.error("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    return null;
}