本文整理匯總了Java中org.apache.http.client.methods.HttpGet類的典型用法代碼示例。如果您正苦於以下問題:Java HttpGet類的具體用法?Java HttpGet怎麽用?Java HttpGet使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpGet類屬於org.apache.http.client.methods包,在下文中一共展示了HttpGet類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: client
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@Test
public void client() throws URISyntaxException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
CloseableHttpResponse response = httpclient.execute(httpget);
}
示例2: getCsrfToken
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
/**
* get the csrf token from the login page's http form
*
* @return the csrf token
*
* @throws IOException
* @param forwardedForHeader
*/
private String getCsrfToken(Header forwardedForHeader) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(configuration.getLoginUrl());
httpGet.setHeader(forwardedForHeader);
CloseableHttpResponse response1 = httpclient.execute(httpGet, context);
try {
logger.debug(response1.getStatusLine().toString());
Optional<String> csrfTokenOpt = extractCsrfTokenAndCloseConnection(response1);
return csrfTokenOpt.orElseThrow(
() -> new IllegalStateException("failed to extract csrf token."));
} finally {
response1.close();
}
} finally {
httpclient.close();
}
}
示例3: getJsonFromCAdvisor
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@Override
public String getJsonFromCAdvisor(String containerId) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.3/containers/docker/" + containerId);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
result = EntityUtils.toString(response.getEntity());
if (logger.isDebugEnabled()) {
logger.debug(result);
}
} finally {
response.close();
}
} catch (Exception e) {
logger.error(containerId, e);
}
return result;
}
示例4: sendGetCommand
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
/**
* sendGetCommand
*
* @param url
* @param parameters
* @return
*/
public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters)
throws ManagerResponseException {
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
try {
CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put(BODY, body);
httpResponse.close();
} catch (Exception e) {
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例5: should_return_status_corresponding_to_match
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@Test
public void should_return_status_corresponding_to_match() throws IOException {
HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");
httpClientMock.onGet("/login").doReturnStatus(200);
httpClientMock.onGet("/abc").doReturnStatus(404);
httpClientMock.onGet("/error").doReturnStatus(500);
HttpResponse ok = httpClientMock.execute(new HttpGet("http://localhost:8080/login"));
HttpResponse notFound = httpClientMock.execute(new HttpGet("http://localhost:8080/abc"));
HttpResponse error = httpClientMock.execute(new HttpGet("http://localhost:8080/error"));
assertThat(ok, hasStatus(200));
assertThat(notFound, hasStatus(404));
assertThat(error, hasStatus(500));
}
示例6: shouldCreateRequestAttachment
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@SuppressWarnings("unchecked")
@Test
public void shouldCreateRequestAttachment() throws Exception {
final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class);
final AttachmentProcessor<AttachmentData> processor = mock(AttachmentProcessor.class);
final HttpClientBuilder builder = HttpClientBuilder.create()
.addInterceptorLast(new AllureHttpClientRequest(renderer, processor));
try (CloseableHttpClient httpClient = builder.build()) {
final HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/hello", server.port()));
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
response.getStatusLine().getStatusCode();
}
}
final ArgumentCaptor<AttachmentData> captor = ArgumentCaptor.forClass(AttachmentData.class);
verify(processor, times(1))
.addAttachment(captor.capture(), eq(renderer));
assertThat(captor.getAllValues())
.hasSize(1)
.extracting("url")
.containsExactly("/hello");
}
示例7: getUser
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
private User getUser(@NotNull Token token) throws IOException, URISyntaxException {
URIBuilder builder = new URIBuilder(PROFILE_URL);
builder.addParameter("access_token", token.getAccessToken());
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(builder.build());
org.apache.http.HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
InputStream inputStream = response.getEntity().getContent();
if (HttpUtilities.success(statusCode)) {
User user = gson.fromJson(new InputStreamReader(inputStream), User.class);
user.setToken(token);
return user;
}
throw new ApiException(HttpStatus.valueOf(statusCode));
}
示例8: check_email_exist
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
public static String check_email_exist(String email_addr) throws Exception {
HttpClient client = new DefaultHttpClient();
String params = "?email_addr=" + email_addr;
HttpGet get = new HttpGet(url + "/check_email_exist" + params);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
JSONObject jsonObject = new JSONObject(result);
int email_exists = jsonObject.getInt("email_exists");
if (email_exists == 1) {
return "SUCCESS";
} else
return "FAIL";
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
return "401 SC_UNAUTHORIZED";
}
return "UNKNOWN ERROR";
}
示例9: CheckForListOfUsersReturned
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
private void CheckForListOfUsersReturned(ArrayList<User> userList,
HttpGet method, String responseString,
String headerString, String responseStatus,
ArrayList<String> subTests) throws CharonException,
ComplianceException, GeneralComplianceException {
subTests.add(ComplianceConstants.TestConstants.PAGINATION_USER_TEST);
if (userList.size() != 2){
//clean up task
for (String id : userIDs) {
CleanUpUser(id);
}
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Pagination Users",
"Response does not contain right number of pagination.",
ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
}
示例10: testRetryAsync3
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@Ignore
public void testRetryAsync3() throws Exception {
final int TIME_OUT = 30000;
ThreadPoolExecutor executor = RetryUtil.createThreadPoolExecutor();
String res = RetryUtil.asyncExecuteWithRetry(new Callable<String>() {
@Override
public String call() throws Exception {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT)
.setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT)
.setStaleConnectionCheckEnabled(true).build();
HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(10).setMaxConnPerRoute(10)
.setDefaultRequestConfig(requestConfig).build();
HttpGet httpGet = new HttpGet();
httpGet.setURI(new URI("http://0.0.0.0:8080/test"));
httpClient.execute(httpGet);
return OK;
}
}, 3, 1000L, false, 6000L, executor);
Assert.assertEquals(res, OK);
// Assert.assertEquals(RetryUtil.EXECUTOR.getActiveCount(), 0);
}
示例11: execute
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@Override
public T execute() throws ClientProtocolException, IOException {
HttpGet get = new HttpGet(InstagramConstants.API_URL + getUrl());
get.addHeader("Connection", "close");
get.addHeader("Accept", "*/*");
get.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
get.addHeader("Cookie2", "$Version=1");
get.addHeader("Accept-Language", "en-US");
get.addHeader("User-Agent", InstagramConstants.USER_AGENT);
HttpResponse response = api.getClient().execute(get);
api.setLastResponse(response);
int resultCode = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity());
get.releaseConnection();
return parseResult(resultCode, content);
}
示例12: should_use_right_host_and_path
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@Test
public void should_use_right_host_and_path() throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.onGet("http://localhost:8080/foo").doReturn("localhost");
httpClientMock.onGet("http://www.google.com").doReturn("google");
httpClientMock.onGet("https://www.google.com").doReturn("https");
HttpResponse localhost = httpClientMock.execute(new HttpGet("http://localhost:8080/foo"));
HttpResponse google = httpClientMock.execute(new HttpGet("http://www.google.com"));
HttpResponse https = httpClientMock.execute(new HttpGet("https://www.google.com"));
assertThat(localhost, hasContent("localhost"));
assertThat(google, hasContent("google"));
assertThat(https, hasContent("https"));
}
示例13: main
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
public static void main(String[] args) {
final CrawlerHttpClient httpClient = HttpInvoker.buildDefault();
for (int i = 0; i < 20; i++) {
new Thread() {
@Override
public void run() {
HttpGet httpGet = new HttpGet("https://passport.jd.com/new/login.aspx");
RequestConfig.Builder builder = RequestConfig.custom()
.setSocketTimeout(ProxyConstant.SOCKET_TIMEOUT)
.setConnectTimeout(ProxyConstant.CONNECT_TIMEOUT)
.setConnectionRequestTimeout(ProxyConstant.REQUEST_TIMEOUT).setRedirectsEnabled(true)
.setCircularRedirectsAllowed(true);
httpGet.setConfig(builder.build());
try {
CloseableHttpResponse execute = httpClient.execute(httpGet);
System.out.println(IOUtils.toString(execute.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
示例14: doNotificationsSearch
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
private JsonNode doNotificationsSearch(String query, String subsearch, Map<?, ?> otherParams, String token)
throws Exception
{
List<NameValuePair> params = Lists.newArrayList();
if( query != null )
{
params.add(new BasicNameValuePair("q", query));
}
if( subsearch != null )
{
params.add(new BasicNameValuePair("type", subsearch));
}
for( Entry<?, ?> entry : otherParams.entrySet() )
{
params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
}
String paramString = URLEncodedUtils.format(params, "UTF-8");
HttpGet get = new HttpGet(context.getBaseUrl() + "api/notification?" + paramString);
HttpResponse response = execute(get, false, token);
return mapper.readTree(response.getEntity().getContent());
}
示例15: getAllMethod
import org.apache.http.client.methods.HttpGet; //導入依賴的package包/類
@RequestMapping(value = "getAllMethod", method = RequestMethod.GET)
public List<MethodDefinition> getAllMethod(
@RequestParam(value = "ipPort", required = true) String ipPort,
@RequestParam(value = "service", required = true) String service) throws Exception {
String methdUrl = "http://" + ipPort + "/service/getAllMethod?service=" + service;
HttpGet request = new HttpGet(methdUrl);
request.addHeader("content-type", "application/json");
request.addHeader("Accept", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String minitorJson = EntityUtils.toString(httpResponse.getEntity());
List<MethodDefinition> allMethods =
gson.fromJson(minitorJson, new TypeToken<List<MethodDefinition>>() {}.getType());
return allMethods;
}
} catch (Exception e) {
throw e;
}
return null;
}