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:com.ifeng.vdn.ip.repository.service.impl.AliIPAddressChecker.java

@Override
public IPAddress ipcheck(String ip) {
    AliIPBean ipaddress = null;/* w ww  .j av  a 2  s .c  om*/

    String url = "http://ip.taobao.com/service/getIpInfo2.php";

    // Create an instance of HttpClient.
    HttpClient clinet = new HttpClient();

    // Create a method instance.
    PostMethod postMethod = new PostMethod(url);

    // Execute the method.
    // Read the response body.
    try {

        postMethod.setParameter("ip", ip);

        int resultCode = clinet.executeMethod(postMethod);

        if (resultCode == HttpStatus.SC_OK) {
            InputStream responseBody = postMethod.getResponseBodyAsStream();

            ObjectMapper mapper = new ObjectMapper();
            ipaddress = mapper.readValue(responseBody, AliIPBean.class);

            log.info(responseBody.toString());
        } else {
            log.error("Method failedd: [{}] , IP: [{}]", postMethod.getStatusCode(), ip);
        }

    } catch (JsonParseException | JsonMappingException | HttpException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return ipaddress;
}

From source file:com.ifeng.vdn.ip.repository.service.impl.IPAddressBaiduChecker.java

@Override
public IPAddress ipcheck(String ip) {

    IPAddress ipaddress = null;/*www . ja  va2s .com*/
    String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + ip
            + "&co=&resource_id=6006&t=1428632527853&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204891062709502876_1428631554303&_=1428631554305";

    // Create an instance of HttpClient.
    HttpClient clinet = new HttpClient();

    // Create a method instance.
    GetMethod getMethod = new GetMethod(url);

    try {
        // Execute the method.
        int statusCode = clinet.executeMethod(getMethod);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failedd: {}", getMethod.getStatusCode());
        } else {
            // Read the response body.
            byte[] responseBody = getMethod.getResponseBody();
            String responseStr = new String(responseBody, "GBK");

            responseStr = responseStr.substring(responseStr.indexOf("(") + 1, responseStr.indexOf(")"));

            ObjectMapper mapper = new ObjectMapper();

            ipaddress = mapper.readValue(responseStr, BaiduIPBean.class);

        }

    } catch (JsonParseException | JsonMappingException | HttpException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return ipaddress;
}

From source file:com.owncloud.android.lib.resources.users.DeletePublicKeyOperation.java

/**
 * @param client Client object/*from w w w  . ja v a2  s. c o m*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    DeleteMethod postMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        postMethod = new DeleteMethod(client.getBaseUri() + PUBLIC_KEY_URL);
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

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

        result = new RemoteOperationResult(status == HttpStatus.SC_OK, postMethod);

        client.exhaustResponse(postMethod.getResponseBodyAsStream());
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Deletion of public key failed: " + result.getLogMessage(), result.getException());
    } finally {
        if (postMethod != null)
            postMethod.releaseConnection();
    }
    return result;
}

From source file:fr.openwide.talendalfresco.rest.client.RestHttpTest.java

public void testRestAuthentication() {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod("http://www.google.com");

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

    try {/*from w  w w. j a  va 2  s.  c  o  m*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        assertEquals(statusCode, HttpStatus.SC_OK);

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

        assertTrue(responseBody != null && responseBody.length != 0);

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        fail("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        fail("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

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

public static String get(HTTPUtils connection, String gnServiceURL, Long id)
        throws GNLibException, GNServerException {
    try {/*from   w  w w . j  a v  a  2 s. co m*/
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Retrieve metadata #" + id);

        String serviceURL = gnServiceURL + "/srv/en/metadata.edit!?id=" + id;

        connection.setIgnoreResponseContentOnSuccess(false);
        String response = connection.get(serviceURL);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Response is " + response.length() + " chars long");

        if (connection.getLastHttpStatus() != HttpStatus.SC_OK)
            throw new GNServerException("Error retrieving metadata in GeoNetwork");

        String version = parseVersion(response);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Metadata " + id + " has version " + version);

        return version;
    } catch (MalformedURLException ex) {
        throw new GNLibException("Bad URL", ex);
    }
}

From source file:com.uber.jenkins.phabricator.conduit.ConduitAPIClientTest.java

@Test
public void testSuccessfullFetch() throws Exception {
    server.register("/api/valid", TestUtils.makeHttpHandler(HttpStatus.SC_OK, "{\"hello\": \"world\"}"));

    client = new ConduitAPIClient(getTestServerAddress(), TestUtils.TEST_CONDUIT_TOKEN);
    JSONObject response = client.perform("valid", emptyParams);
    assertEquals("world", response.getString("hello"));
}

From source file:com.mobilefirst.fiberlink.Authenticator.java

/**
  * Description: Handle sending of request
  * @param post: the object to send/* ww  w.  ja  va2  s  . c o m*/
  */
private final void sendRequest(PostMethod post) {
    try {
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(post);
        System.out.println(
                "------------------------------------Begin Debug: Request Headers----------------------------------------------------------\n");
        Header[] requestHeaders = post.getRequestHeaders();
        for (int cn = 0; cn < requestHeaders.length; cn++) {
            System.out.println(requestHeaders[cn].toString());
        }
        System.out.println(
                "------------------------------------Begin Debug: Response Headers----------------------------------------------------------\n");
        Header[] responseHeaders = post.getResponseHeaders();
        for (int cn = 0; cn < responseHeaders.length; cn++) {
            System.out.println(responseHeaders[cn].toString());
        }
        System.out.println(
                "------------------------------------End Debug----------------------------------------------------------\n");
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("POST method failed: " + post.getStatusLine());
        } else {
            System.out.println("POST method succeeded: " + post.getStatusLine());
            String httpResponse = post.getResponseBodyAsString();
            System.out.println(httpResponse);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.zb.app.biz.service.WeixinTest.java

public void login() {
    httpClient = new HttpClient();
    PostMethod post = new PostMethod(loginUrl);
    post.addParameter(new NameValuePair("username", account));
    post.addParameter(new NameValuePair("pwd", DigestUtils.md5Hex(password)));
    post.addParameter(new NameValuePair("imgcode", ""));
    post.addParameter(new NameValuePair("f", "json"));
    post.setRequestHeader("Host", "mp.weixin.qq.com");
    post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN");

    try {//from  w  ww.  j  ava2  s . c om
        int code = httpClient.executeMethod(post);
        if (HttpStatus.SC_OK == code) {
            String res = post.getResponseBodyAsString();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(res);
            JSONObject _obj = (JSONObject) obj.get("base_resp");
            @SuppressWarnings("unused")
            String msg = (String) _obj.get("err_msg");
            String redirect_url = (String) obj.get("redirect_url");
            Long errCode = (Long) _obj.get("ret");
            if (0 == errCode) {
                isLogin = true;
                token = StringUtils.substringAfter(redirect_url, "token=");
                if (null == token) {
                    token = StringUtils.substringBetween(redirect_url, "token=", "&");
                }
                StringBuffer cookie = new StringBuffer();
                for (Cookie c : httpClient.getState().getCookies()) {
                    cookie.append(c.getName()).append("=").append(c.getValue()).append(";");
                }
                this.cookiestr = cookie.toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ironiacorp.http.impl.httpclient3.PostRequest.java

public HttpJob call() {
    URI uri = (URI) job.getUri();
    PostMethod postMethod = new PostMethod(uri.toString());
    HttpMethodResult result = new HttpMethodResult();
    postMethod.setRequestBody(parameters.toArray(new NameValuePair[0]));

    try {/*from   w  w  w. j  a v  a 2  s.c  o  m*/
        int statusCode = client.executeMethod(postMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + postMethod.getStatusLine());
        }

        InputStream inputStream = postMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            result.setContent(inputStream);
            result.setStatusCode(statusCode);
            job.setResult(result);
        }
    } catch (HttpException e) {
    } catch (IOException e) {
        // In case of an IOException the connection will be released
        // back to the connection manager automatically
    } catch (RuntimeException ex) {
        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        postMethod.abort();
    }

    return job;
}

From source file:com.khipu.lib.java.KhipuService.java

protected String post(Map data) throws KhipuJSONException, IOException {

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Khipu.API_URL + getMethodEndpoint());
    NameValuePair[] params = new NameValuePair[data.keySet().size()];

    int i = 0;/*from w  w w .  j a va 2  s .  co  m*/
    for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); i++) {
        String key = (String) iterator.next();
        params[i] = new NameValuePair(key, (String) data.get(key));
    }

    postMethod.setRequestBody(params);

    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (client.executeMethod(postMethod) == HttpStatus.SC_OK) {
        InputStream stream = postMethod.getResponseBodyAsStream();
        String contentAsString = getContentAsString(stream);
        stream.close();
        postMethod.releaseConnection();
        return contentAsString;
    }
    InputStream stream = postMethod.getResponseBodyAsStream();
    String contentAsString = getContentAsString(stream);
    stream.close();
    postMethod.releaseConnection();
    throw new KhipuJSONException(contentAsString);
}