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:function.GettingPhotos.java

public List<Photo> getPhotos(String userid)
        throws IOException, ParserConfigurationException, SAXException, JSONException {

    getData().setUserid(userid);/* ww  w .ja  v  a  2s .c om*/
    setRequest(getData().getRequestMethod() + getData().getMethodGetPublicPhotos() + "&user_id="
            + getData().getUserid() + "&api_key=" + getData().getKey() + "&format=json");
    System.out.println("GET photos request: " + getRequest());

    setMethod(new GetMethod(getRequest()));
    setStatusCode(getClient().executeMethod(getMethod()));

    if (getStatusCode() != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod().getStatusLine());
    }
    setRstream(null);
    setRstream(getMethod().getResponseBodyAsStream());

    String jstr = toString(getRstream());
    jstr = jstr.substring("jsonFlickrApi(".length(), jstr.length() - 1);

    JSONObject jobj = new JSONObject(jstr);
    JSONArray photos = jobj.getJSONObject("photos").getJSONArray("photo");
    for (int i = 0; i < photos.length(); i++) {
        JSONObject jphoto = photos.getJSONObject(i);
        setPhoto(new Photo());
        getPhoto().setId(jphoto.getString("id"));
        getPhoto().setTitle(jphoto.getString("title"));
        getPhoto().setUserId(jphoto.getString("owner"));
        getPhoto().setSecret(jphoto.getString("secret"));
        getPhoto().setServer(jphoto.getString("server"));
        getListPhotos().add(getPhoto());
    }
    return getListPhotos();
}

From source file:com.bdaum.zoom.net.core.internal.Activator.java

public static InputStream openStream(String url, int timeout)
        throws MalformedURLException, IOException, HttpException {
    URL u = new URL(url);
    URLConnection con = u.openConnection();
    con.setConnectTimeout(timeout);//from w  ww.ja v a  2  s.  com
    con.setReadTimeout(timeout);
    try {
        return new BufferedInputStream(con.getInputStream());
    } catch (IOException e) {
        int responseCode = -1;
        if (con instanceof HttpURLConnection)
            responseCode = ((HttpURLConnection) con).getResponseCode();
        else if (con instanceof HttpsURLConnection)
            responseCode = ((HttpsURLConnection) con).getResponseCode();
        if (responseCode >= 0 && responseCode != HttpStatus.SC_OK)
            throw new HttpException(getStatusText(responseCode), e);
        throw e;
    }
}

From source file:function.GetPhotoInfo.java

private void getPhotoInfo(Photo photo)
        throws IOException, ParserConfigurationException, SAXException, JSONException {

    setRequest(getData().getRequestMethod() + getData().getMethodGetInfo() + "&photo_id=" + photo.getId()
            + "&api_key=" + getData().getKey() + "&format=json");
    System.out.println("GET info request: " + getRequest());

    setMethod(new GetMethod(getRequest()));
    setStatusCode(getClient().executeMethod(getMethod()));

    if (getStatusCode() != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod().getStatusLine());
    }/*from w w  w .j  av a2  s.c  om*/
    setRstream(null);
    setRstream(getMethod().getResponseBodyAsStream());

    String jstr = toString(getRstream());
    jstr = jstr.substring("jsonFlickrApi(".length(), jstr.length() - 1);

    JSONObject jobj = new JSONObject(jstr);
    JSONObject owner = jobj.getJSONObject("photo").getJSONObject("owner");

    photo.setLocation(owner.getString("location"));
    photo.setLat(0);
    photo.setLon(0);

}

From source file:br.com.edu.dbpediaspotlight.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {
    String response = null;//ww  w .jav  a 2 s .  c om
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

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

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:info.smartkit.hairy_batman.demo.MoniterWechatBrowser.java

/**
 * ?URLhtml?/*from   w  w  w  .  j a v a2  s  . co  m*/
 */
@SuppressWarnings("deprecation")
public static String getHttpClientHtml(String url, String code, String userAgent) {
    String html = null;
    @SuppressWarnings("deprecation")
    DefaultHttpClient httpClient = new DefaultHttpClient();// httpClient
    HttpGet httpget = new HttpGet(url);// get?URL
    // Pause for 4 seconds
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
        System.out.println(e1.toString());
    }
    //
    httpget.setHeader("User-Agent", userAgent);
    try {
        // responce
        HttpResponse responce = httpClient.execute(httpget);
        // ?
        int returnCode = responce.getStatusLine().getStatusCode();
        // 200? ?
        if (returnCode == HttpStatus.SC_OK) {
            // 
            HttpEntity entity = responce.getEntity();
            if (entity != null) {
                html = new String(EntityUtils.toString(entity));// html??
            }
        }
    } catch (Exception e) {
        System.out.println("");
        e.printStackTrace();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return html;
}

From source file:$.EndpointIT.java

@Test
    public void testServlet() throws Exception {
        HttpClient client = new HttpClient();

        GetMethod method = new GetMethod(URL);

        try {/* w  w  w .ja  va2 s .  co  m*/
            int statusCode = client.executeMethod(method);

            assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

            String response = method.getResponseBodyAsString(1000);

            assertTrue("Unexpected response body", response.contains("Hello! How are you today?"));
        } finally {
            method.releaseConnection();
        }
    }

From source file:com.taobao.ad.easyschedule.commons.utils.MailUtil.java

/**
 * ??//ww  w.  ja  v a  2  s. c  om
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendMail(String list, String subject, String content) {

    if ("false".equals(Constants.SENDMAIL) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.MAIL_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 2046) {
            strContent = StringUtil.bSubstring(content, 2045);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK")).replaceAll("#content#",
                        URLEncoder.encode(StringUtils.isEmpty(strContent) ? "null" : strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("MailUtil.sendMail statusCode:" + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("MailUtil.sendMail", e);
    }
}

From source file:com.taobao.ad.easyschedule.commons.utils.SmsUtil.java

/**
 * ??/*from  w w  w  .  j  a v  a  2 s.c  o m*/
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendSMS(String list, String subject, String content) {
    if ("false".equals(Constants.SENDSMS) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.SMS_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = subject;
        if (subject.getBytes().length > 150) {
            // ????content?subjectcontent??
            strContent = StringUtil.bSubstring(subject + ":" + content, 149);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK"))
                .replaceAll("#content#", URLEncoder.encode(strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("SmsUtil.sendWangWang statusCode:" + statusCode);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("SmsUtil.sendSMS", e);
    }
}

From source file:com.wafersystems.util.HttpUtil.java

/**
 * URL?//  w w  w. ja  v a 2 s  .c om
 * 
 * @param hClient   HttpClient
 * @param url      URL
 * 
 * @return
 * @throws Exception
 */
public static String openURL(HttpClient hClient, String url) throws Exception {
    HttpMethod method = null;
    try {
        //Get
        method = new GetMethod(url);
        // URL
        int result = hClient.executeMethod(method);
        //cookie?
        //getCookie(method.getURI().getHost(), method.getURI().getPort(), "/" , false , hClient.getState().getCookies());

        //???
        result = checkRedirect(method.getURI().getHost(), method.getURI().getPort(), hClient, method, result);

        if (result != HttpStatus.SC_OK)
            logger.error(method.getPath() + "" + method.getStatusLine().toString() + "\r\n"
                    + method.getResponseBodyAsString());

        return method.getResponseBodyAsString();
    } finally {
        method.releaseConnection();
    }
}

From source file:com.taobao.ad.easyschedule.commons.utils.WangWangUtil.java

/**
 * ??//from   w  ww.  j  a  va  2  s .  c om
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendWangWang(String list, String subject, String content) {

    if ("false".equals(Constants.SENDWANGWANG) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)
            || StringUtils.isEmpty(content)) {
        return;
    }
    try {
        String command = Constants.WANGWANG_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 900) {
            strContent = StringUtil.bSubstring(content, 899);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK")).replaceAll("#content#",
                        URLEncoder.encode(StringUtils.isEmpty(strContent) ? "null" : strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("WangWangUtil.sendWangWang statusCode:" + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("WangWangUtil.sendWangWang", e);
    }
}