下面列出了org.apache.http.client.methods.HttpGet#addHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public GithubProfileInfo info(@NotNull String accessToken, @NotNull GithubEmails emails) throws IOException, GithubException {
HttpGet get = new HttpGet(USER);
get.addHeader("Authorization", "token " + accessToken);
try {
HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();
if (entity == null) throw new IOException(new NullPointerException("HttpEntity is null"));
JsonElement element = parser.parse(new InputStreamReader(entity.getContent()));
if (!element.isJsonObject()) throw new IOException("Response is not of type JsonObject");
JsonObject obj = new JsonObject();
if (obj.has("message")) throw GithubException.fromMessage(obj);
else return new GithubProfileInfo(element.getAsJsonObject(), emails);
} catch (JsonParseException | NullPointerException ex) {
throw new IOException(ex);
} finally {
get.releaseConnection();
}
}
public List<TemplateModel> listTemplate() throws IOException {
HttpGet get = new HttpGet("https://api.github.com/users/vuejs-templates/repos");
get.addHeader("User-Agent","vue-plugin-idea");
get.addHeader("Accept", "application/json");
CloseableHttpResponse res = execute(get);
if(res==null){
return new ArrayList<>();
}else{
List<TemplateModel> templateModels = new Gson().fromJson(EntityUtils.toString(res.getEntity()), new TypeToken<ArrayList<TemplateModel>>() {
}.getType());
if(templateModels==null){
return new ArrayList<>();
}
return templateModels;
}
}
@Test
public void getCertificateTest() throws Exception {
URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.addHeader("Accept", "application/json");
CloseableHttpResponse response1 = httpClient.execute(httpGet);
assertEquals(200, response1.getStatusLine().getStatusCode());
try {
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
}
private String getHttpResponse(String url) {
DefaultHttpClient client = new DefaultHttpClient();
String msg = null;
int retryTimes = 0;
while (msg == null && retryTimes < HTTP_RETRY) {
retryTimes++;
HttpGet request = new HttpGet(url);
try {
request.addHeader("accept", "application/json");
HttpResponse response = client.execute(request);
msg = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.warn("Failed to fetch http response. Retry={}", retryTimes, e);
} finally {
request.releaseConnection();
}
}
return msg;
}
public GithubEmails emails(@NotNull String accessToken) throws IOException, GithubException {
HttpGet get = new HttpGet(EMAILS);
get.addHeader("Authorization", "token " + accessToken);
try {
HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();
if (entity == null) throw new IOException(new NullPointerException("HttpEntity is null"));
JsonElement element = parser.parse(new InputStreamReader(entity.getContent()));
if (element.isJsonArray()) {
return new GithubEmails(element.getAsJsonArray());
} else if (element.isJsonObject()) {
JsonObject obj = new JsonObject();
if (obj.has("message")) throw GithubException.fromMessage(obj);
throw new IOException("I am confused. " + element);
} else {
throw new IOException("What is that? " + element);
}
} catch (JsonParseException | NullPointerException ex) {
throw new IOException(ex);
} finally {
get.releaseConnection();
}
}
private void assertAllOrigin(boolean allOrigins, String[] originList, String[] requestOrigins,
boolean permitted) throws ClientProtocolException, IOException {
configureAllowOrigins(allOrigins, originList);
HttpClient httpclient = HttpClientBuilder.create().build();
HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/untest/simpleGet/HelloThere");
if (requestOrigins != null) {
StringBuilder ob = new StringBuilder();
for (String requestOrigin : requestOrigins) {
ob.append(requestOrigin);
ob.append(' '); // extra trailing space won't hurt.
}
httpget.addHeader("Origin", ob.toString());
}
HttpResponse response = httpclient.execute(httpget);
assertEquals(200, response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String e = IOUtils.toString(entity.getContent());
assertEquals("HelloThere", e); // ensure that we didn't bust the operation itself.
assertOriginResponse(allOrigins, requestOrigins, permitted, response);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
private void checkBook(String address, boolean expected) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(address);
get.addHeader("Accept", "text/plain");
try {
CloseableHttpResponse response = client.execute(get);
assertEquals(200, response.getStatusLine().getStatusCode());
if (expected) {
assertEquals("Book must be available",
"true", EntityUtils.toString(response.getEntity()));
} else {
assertEquals("Book must not be available",
"false", EntityUtils.toString(response.getEntity()));
}
} finally {
// Release current connection to the connection pool once you are done
get.releaseConnection();
}
}
@org.junit.Test
@PerfTest(invocations = 10000,threads = 100)
public void test() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(BASE_URL);
httpGet.addHeader("Authorization", "Bearer " + "521d52b4-9069-4c15-80e9-0d735983aaf2");
CloseableHttpResponse response = null ;
try {
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
// System.out.println(content);
} finally {
if (response != null) {
response.close();
}
httpClient.close();
}
}
/**
* Add custom headers for this download to the HTTP request.
*/
private void addRequestHeaders(InnerState innerState, HttpGet request) {
for (Pair<String, String> header : mInfo.getHeaders()) {
request.addHeader(header.first, header.second);
}
if (innerState.mContinuingDownload) {
if (innerState.mHeaderETag != null) {
request.addHeader("If-Match", innerState.mHeaderETag);
}
request.addHeader("Range", "bytes=" + innerState.mBytesSoFar + "-");
}
}
private JobId submitFromCatalog(HttpGet httpGet, Map<String, String> variables, Map<String, String> genericInfos)
throws SubmissionClosedException, JobCreationException, NotConnectedException, PermissionException {
JobIdData jobIdData = null;
httpGet.addHeader("sessionid", sid);
try (CloseableHttpClient httpclient = getHttpClientBuilder().build();
CloseableHttpResponse response = httpclient.execute(httpGet)) {
jobIdData = restApiClient().submitXml(sid, response.getEntity().getContent(), variables, genericInfos);
} catch (Exception e) {
throwNCEOrPEOrSCEOrJCE(e);
}
return jobId(jobIdData);
}
private Envelope getPath(final String path, final String acceptHeader) throws IOException {
final Envelope envelope;
try(final CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet get = new HttpGet(path);
get.addHeader("Accept", acceptHeader);
final HttpEntity entity = httpClient.execute(get).getEntity();
final String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
envelope = new Envelope(entity.getContentType().getValue(), body);
}
return envelope;
}
/**
* Retrieves business object definition from the herd registration server.
*
* @param namespace the namespace of the business object definition
* @param businessObjectDefinitionName the name of the business object definition
*
* @return the business object definition
* @throws JAXBException if a JAXB error was encountered
* @throws IOException if an I/O error was encountered
* @throws URISyntaxException if a URI syntax error was encountered
* @throws KeyStoreException if a key store exception occurs
* @throws NoSuchAlgorithmException if a no such algorithm exception occurs
* @throws KeyManagementException if key management exception
*/
BusinessObjectDefinition getBusinessObjectDefinition(String namespace, String businessObjectDefinitionName)
throws IOException, JAXBException, URISyntaxException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
LOGGER.info("Retrieving business object definition information from the registration server...");
String uriPathBuilder = HERD_APP_REST_URI_PREFIX + "/businessObjectDefinitions" + "/namespaces/" + namespace + "/businessObjectDefinitionNames/" +
businessObjectDefinitionName;
URIBuilder uriBuilder =
new URIBuilder().setScheme(getUriScheme()).setHost(regServerAccessParamsDto.getRegServerHost()).setPort(regServerAccessParamsDto.getRegServerPort())
.setPath(uriPathBuilder);
URI uri = uriBuilder.build();
try (CloseableHttpClient client = httpClientHelper
.createHttpClient(regServerAccessParamsDto.isTrustSelfSignedCertificate(), regServerAccessParamsDto.isDisableHostnameVerification()))
{
HttpGet request = new HttpGet(uri);
request.addHeader("Accepts", DEFAULT_ACCEPT);
// If SSL is enabled, set the client authentication header.
if (regServerAccessParamsDto.isUseSsl())
{
request.addHeader(getAuthorizationHeader());
}
LOGGER.info(String.format(" HTTP GET URI: %s", request.getURI().toString()));
BusinessObjectDefinition businessObjectDefinition = getBusinessObjectDefinition(httpClientOperations.execute(client, request));
LOGGER.info("Successfully retrieved business object definition from the registration server.");
return businessObjectDefinition;
}
}
private HttpGet buildFetchRequest(Content oldVersion, URI fetchUri) {
HttpGet getRequest = new HttpGet(fetchUri);
if (oldVersion != null) {
DateTime lastModified = oldVersion.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class);
if (lastModified != null) {
getRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate()));
}
final String etag = oldVersion.getAttributes().get(Content.CONTENT_ETAG, String.class);
if (etag != null) {
getRequest.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\"");
}
}
return getRequest;
}
@Test
public void testLotsOfHeadersInRequest_Default_BadRequest() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
// add request headers more than MAX_HEADERS
for (int i = 0; i < (getDefaultMaxHeaders() + 1); ++i) {
get.addHeader(HEADER + i, MESSAGE + i);
}
HttpResponse result = client.execute(get);
Assert.assertEquals(DefaultServer.isH2() ? StatusCodes.SERVICE_UNAVAILABLE : StatusCodes.BAD_REQUEST, result.getStatusLine().getStatusCode()); //this is not great, but the HTTP/2 impl sends a stream error which is translated to a 503. Should not be a big deal in practice
} finally {
client.getConnectionManager().shutdown();
}
}
@Test
public void should401OnGETWithBadEncodedAuthorizationHeader() throws Exception {
final CloseableHttpClient httpclient = HttpClients.createDefault();
final HttpGet httpget = new HttpGet(TestClientFactory.createURLString("?gremlin=1-1"));
httpget.addHeader("Authorization", "Basic: not-base-64-encoded");
try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
assertEquals(401, response.getStatusLine().getStatusCode());
}
}
protected JSONArray fetchTransform(HttpRequestEntity request)
throws IOException {
String transformURI = getSingleParameter(TRANSFORM_PARAMETER,
request.getRequest());
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
HttpGet get = new HttpGet(transformURI);
get.addHeader("Accept", "application/json");
client = HttpClients.createDefault();
response = performRequest(get, client);
HttpEntity responseEntity = response.getEntity();
if (responseEntity == null) {
// TODO proper error reporting
throw new IOException("Could not GET transform JSON from "
+ transformURI + ".");
}
String encoding = null;
if (responseEntity.getContentType() != null) {
encoding = MimeTypes.getCharsetFromContentType(responseEntity.getContentType().getValue());
}
String transform = IOUtils.toString(responseEntity.getContent(),
encoding == null ? "UTF-8" : encoding);
return ParsingUtilities.evaluateJsonStringToArray(transform);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
}
}
@Test
public void sendHttp11RequestWithClose() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
get.addHeader("Connection", "close");
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
Header[] header = result.getHeaders("MyHeader");
Assert.assertEquals("MyValue", header[0].getValue());
} finally {
client.getConnectionManager().shutdown();
}
}
public static List<String> getCustomers(HttpServletRequest req) throws Failure {
KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
HttpClient client = new HttpClientBuilder()
.disableTrustManager().build();
try {
HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/cxf/customerservice/customers");
get.addHeader("Authorization", "Bearer " + session.getTokenString());
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
throw new Failure(response.getStatusLine().getStatusCode());
}
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
try {
return JsonSerialization.readValue(is, TypedList.class);
} finally {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} finally {
client.getConnectionManager().shutdown();
}
}
private HttpResponse generateClientAndReceiveResponseForPriorityTests() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port));
request.addHeader("Accept", "text/xml");
return httpClient.execute(request);
}
public static String getResponseFromGetUrl(String url, String logininfo,
String params) throws Exception {
Log.d("Chen", "url--" + url);
if (null != params && !"".equals(params)) {
url = url + "?";
String[] paramarray = params.split(",");
for (int index = 0; null != paramarray && index < paramarray.length; index++) {
if (index == 0) {
url = url + paramarray[index];
} else {
url = url + "&" + paramarray[index];
}
}
}
HttpGet httpRequest = new HttpGet(url);
httpRequest.addHeader("Cookie", logininfo);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
// DefaultHttpClient httpclient = new DefaultHttpClient();
StringBuffer sb = new StringBuffer();
try {
HttpResponse httpResponse = httpclient.execute(httpRequest);
String inputLine = "";
// Log.d("Chen","httpResponse.getStatusLine().getStatusCode()"+httpResponse.getStatusLine().getStatusCode());
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStreamReader is = new InputStreamReader(httpResponse
.getEntity().getContent());
BufferedReader in = new BufferedReader(is);
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
} else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
return "not_modify";
}
} catch (Exception e) {
e.printStackTrace();
return "net_error";
} finally {
httpclient.getConnectionManager().shutdown();
}
return sb.toString();
}