Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod GetMethod.

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:function.SearchPhotos.java

public List<Photo> searchPhoto(String text, int page)
        throws IOException, ParserConfigurationException, SAXException, JSONException {

    setRequest(getData().getRequestMethod() + getData().getMethodSearchPhotos() + "&text=" + text
            + "&sort=relevance" + "&page=" + page + "&api_key=" + getData().getKey() + "&format=json");
    System.out.println("GET search request: " + getRequest());

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

    if (getStatusCode() != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + getMethod().getStatusLine());
    }// w  ww . j av a  2 s . c o m
    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:att.jaxrs.server.TagService.java

@GET
@Path("/tags")
public Response getTags() {
    GetMethod get = new GetMethod(Constants.SELECT_ALL_TAG_OPERATION);
    TagCollection tag = null;//from w ww  .j a v  a 2s .co m
    try {

        HttpClient httpClient = new HttpClient();
        try {
            int result = httpClient.executeMethod(get);
            System.out.println(Constants.RESPONSE_STATUS_CODE + result);
            tag = Marshal.unmarshal(TagCollection.class, get.getResponseBodyAsStream());

        } finally {
            get.releaseConnection();

        }
    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return Response.ok(tag).build();

}

From source file:de.loercher.localpress.connector.HttpClientJob.java

@Override
public void run() {
    try {/*from  w ww.j a va 2 s  .  c o m*/
        MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(connectionManager);
        HttpMethod method = new GetMethod(url);
        client.executeMethod(method);

        System.out.println(new String(method.getResponseBody()));

    } catch (IOException ex) {
        Logger.getLogger(HttpClientJob.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.du.penrose.systems.util.HttpClientUtils_2.java

static public WebPage academicSearch(URL initialLink) {
    WebPage wp = new WebPage();
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(initialLink.toString());

    getMethod.setFollowRedirects(true);//  w  w  w .j  a va2s.  c  om

    try {

        //         System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        //         System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        //         System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");
        //         System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
        //         
        getMethod.setRequestHeader("User-Agent",
                "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); // in case they check
        int statusCode = client.executeMethod(getMethod);
        String contents = getMethod.getResponseBodyAsString();
        String formPage = getMethod.getURI().toString(); // page we were sent to.
        wp.setStatus(statusCode);
        wp.setWebPage(contents);
        //         System.out.println();System.out.println();System.out.println();System.out.println();System.out.println(contents);   

        String sid = getSID(contents);
        String postURL = "http://web.ebscohost.com/ehost/search?vid=1&hid=9&sid=" + sid;

        PostMethod postMethod = new PostMethod(
                "http://web.ebscohost.com/ehost/search?vid=1&hid=9&sid=c3220986-66e4-4fd1-ba6a-30504f3694ad%40sessionmgr13");
        postMethod.setRequestHeader("User-Agent",
                "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); // in case they check                             

        // postMethod.setFollowRedirects( true ); causes error
        postMethod.setParameter(SESSION_ID, sid);

        setResolution(postMethod, contents);
        setNonchangingFields(postMethod);

        statusCode = client.executeMethod(postMethod);

        if (statusCode > 300) {
            String resultsPage = getMethod.getURI().toString(); // page we were sent to.
            getMethod = new GetMethod(resultsPage);
            getMethod.setRequestHeader("User-Agent",
                    "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); // in case they check
            statusCode = client.executeMethod(getMethod);

            contents = getMethod.getResponseBodyAsString();
            wp.setStatus(statusCode);
            wp.setWebPage(contents);
        }
        contents = postMethod.getResponseBodyAsString();

        wp.setStatus(statusCode);
        wp.setWebPage(contents);

        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println(contents);
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        getMethod.releaseConnection();
    }
    return wp;
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3Util.java

/**
 * ?url?ResponseBody,method=get/*  w  ww .  java 2s . co  m*/
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

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

/**
 * ??//from  w  w w . j  a v a2  s  .  c o  m
 * 
 * @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:name.chengchao.myhttpclient.version3_1.HttpClient3UtilError.java

/**
 * ?url?ResponseBody,method=get//  ww w .  ja va 2s  . c  o m
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    // method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:javaapplicationclientrest.ControllerCliente.java

public void listarNoticias() {
    GetMethod list = new GetMethod(Constants.GET_NOTICIAS);
    String responseStatus = "";
    String response = "";
    try {/*from   w w  w .  ja  v  a2s  . c  om*/
        http.executeMethod(list);
        responseStatus = list.getStatusText();
        response = list.getResponseBodyAsString();
    } catch (IOException ex) {
        Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("status: " + responseStatus + "\n" + "Responde: " + response);

}

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

/**
 * ??/* ww  w .j  av a2s  .  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:function.GettingPhotos.java

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

    getData().setUserid(userid);//from www  .j  av  a  2  s . 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();
}