本文整理匯總了Java中org.apache.http.client.methods.HttpGet.addHeader方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpGet.addHeader方法的具體用法?Java HttpGet.addHeader怎麽用?Java HttpGet.addHeader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.apache.http.client.methods.HttpGet
的用法示例。
在下文中一共展示了HttpGet.addHeader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: search
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public String search(String query) {
try {
String url = "?text=" + Utility.urlEncode(query) + "&confidence=" + confidence;
HttpGet httpGet = new HttpGet(URL + url);
httpGet.addHeader("Accept", "application/json");
HttpResponse response = client.execute(httpGet);
// Error Scenario
if(response.getStatusLine().getStatusCode() >= 400) {
logger.error("Spotlight Service could not answer due to: " + response.getStatusLine());
return null;
}
else {
String entities = EntityUtils.toString(response.getEntity());
JsonNode entity = new ObjectMapper().readTree(entities).get("Resources").get(0);
return entity.get("@URI").getTextValue();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例2: getBalance
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public static double getBalance() {
String temp;
HttpClientBuilder hcb = HttpClientBuilder.create();
HttpClient client = hcb.build();
HttpGet request = new HttpGet(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/summary");
request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
try {
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
JSONObject accountDetails = new JSONObject(result.toString()).getJSONObject("account");
temp = accountDetails.getString("balance");
return Double.parseDouble(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
示例3: downloadConfig
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
private String[] downloadConfig(String url) throws Exception {
try {
HttpClient client = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
requestGet.addHeader("X-Android-MODEL", Build.MODEL);
requestGet.addHeader("X-Android-SDK_INT", Integer.toString(Build.VERSION.SDK_INT));
requestGet.addHeader("X-Android-RELEASE", Build.VERSION.RELEASE);
requestGet.addHeader("X-App-Version", AppVersion);
requestGet.addHeader("X-App-Install-ID", AppInstallID);
requestGet.setHeader("User-Agent", System.getProperty("http.agent"));
HttpResponse response = client.execute(requestGet);
String configString = EntityUtils.toString(response.getEntity(), "UTF-8");
String[] lines = configString.split("\\n");
return lines;
} catch (Exception e) {
throw new Exception(String.format("Download config file from %s failed.", url));
}
}
示例4: executeHttpGet
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
/**
* Performs HTTP Get request with OAuth authentication for the endpoint with
* the given path with the given HTTP headers.
*
* @param path
* the path to be called.
* @param headers
* map with HTTP header names and values to be included in the
* request.
* @return the CloseableHttpResponse object.
* @throws ClientProtocolException
* @throws IOException
*/
CloseableHttpResponse executeHttpGet(String path, Map<String, String> headers)
throws ClientProtocolException, IOException {
logger.debug(DEBUG_EXECUTING_HTTP_GET_FOR, baseUri, path);
HttpGet httpGet = createHttpGet(baseUri + path);
for (String header : headers.keySet()) {
httpGet.addHeader(header, headers.get(header));
}
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);
logger.debug(DEBUG_EXECUTED_HTTP_GET_FOR, baseUri, path);
return response;
}
示例5: get
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public static HttpResponse get(String url, Map<String, String> header) {
int statusCode = 0;
String responseBody = "";
try {
logger.info(String.format("Getting url: %s", url));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
statusCode = httpResponse.getStatusLine().getStatusCode();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()))) {
responseBody = IOUtils.toString(reader);
logger.info(String.format("Finished getting url: %s, Http status: %s, Response body: %s",
url, statusCode, truncateLogString(responseBody)));
}
}
}
return new HttpResponse(statusCode, responseBody);
} catch (Exception ex) {
String msg = String.format("Failed getting url: %s", url);
logger.warn(msg, ex);
throw new RuntimeException(msg, ex);
}
}
示例6: users
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public void users() throws IOException, URISyntaxException {
HttpGet req = new HttpGet(url(USERS_URL));
req.addHeader("Content-Type", "application/json");
req.addHeader("Authorization", "Bearer " + this.token);
CloseableHttpResponse resp = this.client.execute(req);
this.users = gson.fromJson(IOUtils.toString(resp.getEntity().getContent(), "UTF-8"), Map.class);
resp.close();
}
示例7: downloadData
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public void downloadData(String symbol, long startDate, long endDate, String crumb) {
String filename = String.format("%s.csv", symbol);
String url = String.format("https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=1d&events=history&crumb=%s", symbol, startDate, endDate, crumb);
HttpGet request = new HttpGet(url);
System.out.println(url);
request.addHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13");
try {
HttpResponse response = client.execute(request, context);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String reasonPhrase = response.getStatusLine().getReasonPhrase();
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(String.format("statusCode: %d", statusCode));
System.out.println(String.format("reasonPhrase: %s", reasonPhrase));
if (entity != null) {
BufferedInputStream bis = new BufferedInputStream(entity.getContent());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filename)));
int inByte;
while((inByte = bis.read()) != -1)
bos.write(inByte);
bis.close();
bos.close();
}
HttpClientUtils.closeQuietly(response);
} catch (Exception ex) {
System.out.println("Exception");
System.out.println(ex);
}
}
示例8: getHeaders
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public String getHeaders(String url, String cookie, String headerName) {
HttpGet get = new HttpGet(url);
if(StringUtils.isNotBlank(cookie))
get.addHeader("cookie", cookie);
res(get);
Header[] headers = get.getHeaders(headerName);
return headers == null ? null : headers.toString();
}
示例9: doGet
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
示例10: testProtectedWithAuthorization
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
/**
* Username is provided, without authority but in white list gives 200
*/
@Test
public void testProtectedWithAuthorization() throws IOException {
final HttpGet message = new HttpGet(BASE_URI + "/" + SESSION_RESOURCE);
// Add TARS headers
message.addHeader("sm_universalid", DEFAULT_USER);
final HttpResponse response = httpclient.execute(message);
try {
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
final SessionSettings settings = new ObjectMapperTrim().readValue(response.getEntity().getContent(), SessionSettings.class);
// Check the application settings (session scope)
Assert.assertNotNull(settings);
Assert.assertNotNull(settings.getRoles());
Assert.assertEquals(2, settings.getRoles().size());
Assert.assertTrue(settings.getRoles().contains("USER"));
Assert.assertTrue(settings.getRoles().contains("test"));
Assert.assertNotNull(settings.getAuthorizations());
Assert.assertNotNull(settings.getBusinessAuthorizations());
Assert.assertEquals(DEFAULT_USER, settings.getUserName());
// Check the application settings (singleton)
Assert.assertNotNull(settings.getApplicationSettings());
Assert.assertNotNull(settings.getApplicationSettings().getBuildNumber());
Assert.assertNotNull(settings.getApplicationSettings().getBuildTimestamp());
Assert.assertNotNull(settings.getApplicationSettings().getBuildVersion());
} finally {
IOUtils.closeQuietly(response.getEntity().getContent());
}
}
示例11: getStatusAdmin
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
/**
* Retorna o status de um administrador da conta digital
* @param email: E-mail do administrador à ser consultado
* @return String: Descrição do status
*/
public String getStatusAdmin(String email) throws IOException, PJBankException {
PJBankClient client = new PJBankClient(this.endPoint.concat("/administradores/").concat(email));
HttpGet httpGet = client.getHttpGetClient();
httpGet.addHeader("x-chave-conta", this.chave);
String response = EntityUtils.toString(client.doRequest(httpGet).getEntity());
JSONObject responseObject = new JSONObject(response);
return responseObject.getString("msg");
}
示例12: getObjects
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
/**
* Get a list of objects for the given query
*
* @param moduleName
* the modulenname
* @param dataModelName
* the name of the datamodels
* @param query
* ApiOmat query string, may be null to append no query
* @param additionalRequestHeaders
* additional headers to be set
* @return request object to check status codes and return values
*/
public Response getObjects( String moduleName, String dataModelName, String query,
Map<String, String> additionalRequestHeaders )
{
final HttpGet request = new HttpGet(
this.yambasBase + "apps/" + this.appName + "/models/" + moduleName + "/" + dataModelName +
( query == null ? "" : "?q=" + query ) );
setAuthorizationHeader( request );
request.addHeader( "ContentType", "application/json" );
request.addHeader( "x-apiomat-apikey", this.apiKey );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
request.addHeader( "x-apiomat-sdkVersion", this.sdkVersion );
if ( additionalRequestHeaders != null )
{
additionalRequestHeaders.forEach( ( name, value ) -> request.addHeader( name, value ) );
}
try
{
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
示例13: isRaisingTrend
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
public boolean isRaisingTrend() {
double aggregate = 0;
double SMA100;
HttpClientBuilder hcb = HttpClientBuilder.create();
HttpClient client = hcb.build();
HttpGet request = new HttpGet(RequestURI.baseURL+"/v1/candles?instrument=EUR_USD&count=100&granularity=M30&candleFormat=midpoint");
request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
try {
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
JSONObject resultJson = new JSONObject(result.toString());
JSONArray candles = resultJson.getJSONArray("candles");
for (int i=0; i<candles.length(); i++) {
double closePrice = Double.parseDouble(candles.getJSONObject(i).get("closeMid").toString());
aggregate += closePrice;
}
SMA100 = Trading.round(aggregate/100, 5);
if (getLatestCandle().getClose() > SMA100) return true;
else return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
示例14: load
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
/**
* Gets the input stream from a response entity. If the entity is gzipped then this will get a
* stream over the uncompressed data.
*
* @param entity the entity whose content should be read
* @return the input stream to read from
* @throws IOException
*/
public HttpResponse load (Uri uri) throws IOException{
if (DEBUG) Log.d(TAG, "Requesting: " + uri);
HttpGet httpGet = new HttpGet(uri.toString());
httpGet.addHeader("Accept-Encoding", "gzip");
return mHttpClient.execute(httpGet);
}
示例15: createHttpGet
import org.apache.http.client.methods.HttpGet; //導入方法依賴的package包/類
private HttpGet createHttpGet(String uri) {
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader(basicAuthorizationHeader);
httpGet.addHeader(apikeyHeader);
return httpGet;
}