Example usage for org.apache.http.client.methods RequestBuilder get

List of usage examples for org.apache.http.client.methods RequestBuilder get

Introduction

In this page you can find the example usage for org.apache.http.client.methods RequestBuilder get.

Prototype

public static RequestBuilder get() 

Source Link

Usage

From source file:cn.jumper.study.http.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http");

    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

    try {/* ww  w. j a  v  a 2 s  . c o m*/
        HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp");
        httpget.setConfig(config);
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        String code = "";
        try {
            HttpUriRequest httpgetCode = RequestBuilder.get()
                    .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build();

            /*
             * HttpGet httpgetCode = new HttpGet(
             * "http://www.qufuev.com/admin/inc/checkcode.asp");
             * httpgetCode.setConfig(config);
             */

            System.out.println("Executing request " + httpgetCode.getRequestLine());
            System.out.println("========================================================");
            System.out.println("==httpget header ==");
            for (Header header : httpgetCode.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            System.out.println("==httpget header ==");

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                public String handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        System.out.println("==respons header ==");
                        for (Header header : response.getAllHeaders()) {
                            System.out.println(header.getName() + ":" + header.getValue());
                        }
                        System.out.println("==respons header ==");
                        String fileName = System.currentTimeMillis() + "";
                        DataOutputStream dataOutputStream = new DataOutputStream(
                                new FileOutputStream("d://test//e3//" + fileName + ".jpg"));
                        dataOutputStream.write(EntityUtils.toByteArray(entity));
                        dataOutputStream.close();
                        return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg");
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            code = httpclient.execute(httpgetCode, responseHandler);
            System.out.println("ClientFormLogin.main()-CheckCode:" + code);
            System.out.println("----------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp"))
                .addParameter("UserName", "username").addParameter("Password", "password")
                .addParameter("CheckCode", code).setConfig(config).build();

        System.out.println("========================================================");
        System.out.println("==httpget header ==");
        for (Header header : login.getAllHeaders()) {
            System.out.println(header.getName() + ":" + header.getValue());
        }

        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form post: " + response2.getStatusLine());
            // EntityUtils.consume(entity);
            System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK"));

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:zz.pseas.ghost.login.taobao.MTaobaoLogin.java

public static void main(String[] args) throws UnsupportedEncodingException {

    String tbuserNmae = "TBname";
    String tbpassWord = "TBpasssword";

    GhostClient iPhone = new GhostClient("utf-8");
    String ans = iPhone.get("https://login.m.taobao.com/login.htm");

    Document doc = Jsoup.parse(ans);
    String url = doc.select("form#loginForm").first().attr("action");

    String _tb_token = doc.select("input[name=_tb_token_]").first().attr("value");

    String sid = doc.select("input[name=sid]").first().attr("value");
    System.out.println(_tb_token);
    System.out.println(sid);/*  www . j  av  a  2  s  .c om*/
    System.out.println(url);

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("TPL_password", tbpassWord);
    map.put("TPL_username", tbuserNmae);
    map.put("_tb_token_", _tb_token);
    map.put("action", "LoginAction");
    map.put("event_submit_do_login", "1");
    map.put("loginFrom", "WAP_TAOBAO");
    map.put("sid", sid);

    String location = null;
    while (true) {
        CommonsPage commonsPage = iPhone.postForPage(url, map);
        location = commonsPage.getHeader("Location");
        String postAns = new String(commonsPage.getContents(), "utf-8");
        if (StringUtil.isNotEmpty(location) && StringUtil.isEmpty(postAns)) {
            break;
        }

        String s = Jsoup.parse(postAns).select("img.checkcode-img").first().attr("src");
        String imgUrl = "https:" + s;

        byte[] bytes = iPhone.getBytes(imgUrl);
        FileUtil.writeFile(bytes, "g:/tbCaptcha.jpg");

        String wepCheckId = Jsoup.parse(postAns).select("input[name=wapCheckId]").val();
        String captcha = null;
        map.put("TPL_checkcode", captcha);
        map.put("wapCheckId", wepCheckId);
    }

    iPhone.get(location);

    String tk = iPhone.getCookieValue("_m_h5_tk");
    if (StringUtil.isNotEmpty(tk)) {
        tk = tk.split("_")[0];
    } else {
        tk = "undefined";
    }

    String url2 = genUrl(tk);
    String ans1 = iPhone.get(url2);
    System.out.println(url2);
    System.out.println(ans1);

    tk = iPhone.getCookieValue("_m_h5_tk").split("_")[0];
    if (StringUtil.isEmpty(tk)) {
        tk = "undefined";
    }
    System.out.println(tk);
    url2 = genUrl(tk);
    iPhone.showCookies();
    RequestConfig requestConfig = RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8888)).build();

    HttpUriRequest get = RequestBuilder.get().setConfig(requestConfig)
            //.addHeader("User-Agent","Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16")
            .addHeader("Host", "api.m.taobao.com").setUri(url2).build();

    ans1 = iPhone.execute(get);

    System.out.println(ans1);

}

From source file:org.keycloak.authorization.client.util.Http.java

public <R> HttpMethod<R> get(String path) {
    return method(RequestBuilder.get().setUri(path));
}

From source file:com.optimizely.ab.OptimizelyHttpClientTest.java

@Test
public void testExecute() throws IOException {
    HttpUriRequest httpUriRequest = RequestBuilder.get().build();
    ResponseHandler<Boolean> responseHandler = response -> null;

    CloseableHttpClient mockHttpClient = mock(CloseableHttpClient.class);
    when(mockHttpClient.execute(httpUriRequest, responseHandler)).thenReturn(true);

    OptimizelyHttpClient optimizelyHttpClient = new OptimizelyHttpClient(mockHttpClient);
    assertTrue(optimizelyHttpClient.execute(httpUriRequest, responseHandler));
}

From source file:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java

public static QingCloudRequestBuilder get(QingCloud qingCloud) {
    return new QingCloudRequestBuilder(qingCloud, RequestBuilder.get());
}

From source file:cf.spring.servicebroker.AbstractServiceBrokerTest.java

protected JsonNode loadCatalog(CloseableHttpClient client) throws IOException {
    final HttpUriRequest catalogRequest = RequestBuilder.get()
            .setUri("http://localhost:8080" + Constants.CATALOG_URI).build();
    final CloseableHttpResponse response = client.execute(catalogRequest);
    assertEquals(response.getStatusLine().getStatusCode(), 200);
    final String body = StreamUtils.copyToString(response.getEntity().getContent(), Charset.defaultCharset());

    final ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree(body);
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpGet(String url, List<NameValuePair> params) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   ww  w .  j  av a2 s. co m
        RequestBuilder rb = RequestBuilder.get().setUri(new URI(url));
        for (NameValuePair hp : params) {
            rb.addParameter(hp.getName(), hp.getValue());
        }
        rb.addHeader("accept", "application/json");
        HttpUriRequest uriRequest = rb.build();
        HttpResponse response = httpclient.execute(uriRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(br);
        return je.getAsJsonObject();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return null;
}

From source file:org.eclipse.vorto.repository.RestClient.java

@SuppressWarnings("restriction")
public <Result> Result executeGet(String query, final Function<String, Result> responseConverter)
        throws ClientProtocolException, IOException {

    CloseableHttpClient client = HttpClients.custom().build();

    HttpUriRequest request = RequestBuilder.get().setConfig(createProxyConfiguration())
            .setUri(createQuery(query)).build();
    return client.execute(request, new ResponseHandler<Result>() {

        @Override/*from  ww w .j a v  a  2 s.c o m*/
        public Result handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            return responseConverter.apply(IOUtils.toString(response.getEntity().getContent()));
        }
    });
}

From source file:de.cuseb.bilderbuch.images.DeviantArtImageSearch.java

@Override
public List<Image> searchImages(String query) throws ImageSearchException {

    List<Image> result = new ArrayList<Image>();

    try {/*from   ww  w .  java2s.co m*/
        HttpClient client = httpClientProviderService.getHttpClient();
        HttpUriRequest request = RequestBuilder.get().setUri("http://backend.deviantart.com/rss.xml")
                .addParameter("limit", "10").addParameter("q", "in=photography " + query).build();
        HttpResponse response = client.execute(request);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(response.getEntity().getContent());

        NodeList items = document.getElementsByTagName("item");
        for (int i = 0; i < items.getLength(); i++) {
            Element item = (Element) items.item(i);
            NodeList title = item.getElementsByTagName("title");
            NodeList content = item.getElementsByTagName("media:content");
            if (content.getLength() > 0) {
                Node url = content.item(0).getAttributes().getNamedItem("url");
                if (url != null) {
                    Image image = new Image();
                    image.setSource("deviantart");
                    image.setUrl(url.getTextContent());
                    image.setTitle(title.item(0).getFirstChild().getTextContent());
                    result.add(image);
                }
            }
        }
    } catch (Exception e) {
        log.error("searchImages", e);
    }
    return result;
}

From source file:de.cuseb.bilderbuch.images.BingImageSearch.java

@Override
public List<Image> searchImages(String query) throws ImageSearchException {

    List<Image> result = new ArrayList<Image>();

    try {//from w  w w  . j  av a2s  .  co  m
        HttpClient client = httpClientProviderService.getHttpClientWithBasicAuth("", password);
        HttpUriRequest request = RequestBuilder.get()
                .setUri("https://api.datamarket.azure.com/Bing/Search/v1/Image")
                .addParameter("Query", "'" + query + "'").addParameter("$format", "json").build();
        HttpResponse response = client.execute(request);

        JsonNode json = objectMapper.readTree(response.getEntity().getContent());
        Iterator<JsonNode> results = json.get("d").get("results").elements();

        while (results.hasNext()) {
            JsonNode next = results.next();
            Image image = new Image();
            image.setSource("bing");
            image.setTitle(next.get("Title").textValue());
            image.setUrl(next.get("MediaUrl").textValue());
            result.add(image);
        }

    } catch (IOException e) {
        log.error("searchImages", e);
    }

    return result;
}