Java源码示例:kong.unirest.UnirestException
示例1
/**
* Make the authentication request to the Mojang session server. We need to do this as the one sent by the
* real client will have had our 'fake' public key instead of the server's real one, and as such the server will
* not accept the connection.
* @param hash hash based on the server information.
*/
public void makeRequest(String hash) throws UnirestException {
AuthDetails details = profiles.getAuthDetails();
Map<String, String> body = new HashMap<>();
body.put("accessToken", details.getAccessToken());
body.put("selectedProfile", details.getUuid());
body.put("serverId", hash);
HttpResponse<String> str = Unirest.post(AUTH_URL)
.header("Content-Type", "application/json")
.body(new Gson().toJson(body))
.asString();
if (str.getStatus() != STATUS_SUCCESS) {
throw new RuntimeException("Client not authenticated! " + str.getBody());
} else {
System.out.println("Successfully authenticated user with Mojang session server.");
}
}
示例2
public static IPFSClusterPinningService connect(String host, Integer port, String protocol) {
ValidatorUtils.rejectIfEmpty("host", host);
ValidatorUtils.rejectIfNegative("port", port);
ValidatorUtils.rejectIfDifferentThan("protocol", protocol, "http", "https");
try {
log.trace("call GET {}://{}:{}/id", protocol, host, port);
HttpResponse<String> response = Unirest.get(String.format(BASE_URI + "/id", protocol, host, port))
.asString()
.ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
log.info("Connected to IPFS-Cluster [protocol: {}, host: {}, port: {}]: Info {}", protocol, host, port,
response.getBody());
return new IPFSClusterPinningService(host, port, protocol);
} catch (UnirestException ex) {
String msg = String.format("Error whilst connecting to IPFS-Cluster [host: %s, port: %s]", host, port);
log.error(msg, ex);
throw new ConnectionException(msg, ex);
}
}
示例3
@Override
public void pin(String cid) {
log.debug("pin CID {} on IPFS-cluster", cid);
try {
ValidatorUtils.rejectIfEmpty("cid", cid);
log.trace("call POST {}://{}:{}/pins/{}", protocol, host, port, cid);
Unirest.post(String.format(BASE_URI + "/pins/%s", protocol, host, port, cid))
.asString()
.ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
log.debug("CID {} pinned on IPFS-cluster", cid);
} catch (UnirestException ex) {
String msg = String.format("Error whilst sending request to IPFS-Cluster [host: %s, port: %s]", host, port);
log.error(msg, ex);
throw new TechnicalException(msg, ex);
}
}
示例4
@Override
public void unpin(String cid) {
log.debug("unpin CID {} on IPFS-cluster", cid);
try {
ValidatorUtils.rejectIfEmpty("cid", cid);
log.trace("call DELETE {}://{}:{}/pins/{}", protocol, host, port, cid);
Unirest.delete(String.format(BASE_URI + "/pins/%s", protocol, host, port, cid))
.asString()
.ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
log.debug("unpin {} pinned on IPFS-cluster", cid);
} catch (UnirestException ex) {
String msg = String.format("Error whilst sending request to IPFS-Cluster [host: %s, port: %s]", host, port);
log.error(msg, ex);
throw new TechnicalException(msg, ex);
}
}
示例5
@Override
public List<String> getTracked() {
log.debug("get pinned files on IPFS-cluster");
try {
log.trace("GET {}://{}:{}/pins", protocol, host, port);
HttpResponse<String> response = Unirest.get(String.format(BASE_URI + "/pins", protocol, host, port))
.asString()
.ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
log.debug("response: {}", response);
IPFSClusterTrackedResponse result = mapper.readValue(response.getBody(), IPFSClusterTrackedResponse.class);
log.debug("get pinned files on IPFS-cluster");
return result.getPins();
} catch (UnirestException | IOException ex) {
log.error("Exception converting HTTP response to JSON", ex);
throw new TechnicalException("Exception converting HTTP response to JSON", ex);
}
}
示例6
@Override
public List<String> getTracked() {
log.debug("get pinned files on Pinata");
try {
log.trace("GET {}/data/pinList?status=pinned&pageLimit=1000", endpoint);
HttpResponse<String> response = Unirest.get(endpoint + "/data/pinList?status=pinned&pageLimit=1000")
.header(HEADER_API_KEY, apiKey)
.header(HEADER_SECRET_API_KEY, secretApiKey)
.asString()
.ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
log.trace("response: {}", response.getBody());
PinataTrackedResponse result = mapper.readValue(response.getBody(), PinataTrackedResponse.class);
log.debug("get pinned files on Pinata [count: {}]", result.getCount());
return result.getRows()
.stream()
.map(r -> r.getHash())
.collect(Collectors.toList());
} catch (UnirestException | IOException ex) {
log.error("Exception whilst requesting the tracked data", ex);
throw new TechnicalException("Exception whilst requesting the tracked data", ex);
}
}
示例7
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
try {
final HttpResponse<JsonNode> response = ui.get(url)
.header("accept", "application/json")
.asJson();
if (response.getStatus() == 200) {
if (response.getBody() != null && response.getBody().getObject() != null) {
final String latest = response.getBody().getObject().getString("version");
meta.setLatestVersion(latest);
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
}
} catch (UnirestException e) {
handleRequestException(LOGGER, e);
}
}
return meta;
}
示例8
private boolean performVersionCheck(final MetaModel meta, final Component component) {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final String url = String.format(baseUrl + VERSION_QUERY_URL, component.getPurl().getName().toLowerCase());
try {
final HttpResponse<JsonNode> response = ui.get(url)
.header("accept", "application/json")
.asJson();
if (response.getStatus() == 200) {
if (response.getBody() != null && response.getBody().getObject() != null) {
final JSONArray versions = response.getBody().getObject().getJSONArray("versions");
final String latest = versions.getString(versions.length()-1); // get the last version in the array
meta.setLatestVersion(latest);
}
return true;
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
}
} catch (UnirestException e) {
handleRequestException(LOGGER, e);
}
return false;
}
示例9
/**
* Submits the payload to the NPM service
*/
private List<Advisory> submit(final JSONObject payload) throws UnirestException {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final HttpResponse<JsonNode> jsonResponse = ui.post(API_BASE_URL)
.header("user-agent", "npm/6.1.0 node/v10.5.0 linux x64")
.header("npm-in-ci", "false")
.header("npm-scope", "")
.header("npm-session", generateRandomSession())
.header("content-type", "application/json")
.body(payload)
.asJson();
if (jsonResponse.getStatus() == 200) {
final NpmAuditParser parser = new NpmAuditParser();
return parser.parse(jsonResponse.getBody());
} else {
handleUnexpectedHttpResponse(LOGGER, API_BASE_URL, jsonResponse.getStatus(), jsonResponse.getStatusText());
}
return new ArrayList<>();
}
示例10
/**
* Submits the payload to the Sonatype OSS Index service
*/
private List<ComponentReport> submit(final JSONObject payload) throws UnirestException {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final HttpResponse<JsonNode> jsonResponse = ui.post(API_BASE_URL)
.header(HttpHeaders.ACCEPT, "application/json")
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.header(HttpHeaders.USER_AGENT, ManagedHttpClientFactory.getUserAgent())
.basicAuth(apiUsername, apiToken)
.body(payload)
.asJson();
if (jsonResponse.getStatus() == 200) {
final OssIndexParser parser = new OssIndexParser();
return parser.parse(jsonResponse.getBody());
} else {
handleUnexpectedHttpResponse(LOGGER, API_BASE_URL, jsonResponse.getStatus(), jsonResponse.getStatusText());
}
return new ArrayList<>();
}
示例11
public UUID createProject(String name, String version) throws UnirestException {
final UnirestInstance ui = UnirestFactory.getUnirestInstance();
final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/project")
.header("Content-Type", "application/json")
.header("X-API-Key", apiKey)
.body(new JSONObject()
.put("name", name)
.put("version", version)
)
.asJson();
if (response.getStatus() == 201) {
return UUID.fromString(response.getBody().getObject().getString("uuid"));
}
System.out.println("Error creating project " + name + " status: " + response.getStatus());
return null;
}
示例12
public static void main(String[] args) {
Map<Customer, JSONArray> allTodos = new HashMap<>();
try {
CustomerDao dao = new RestCustomerDao();
Collection<Customer> customers = dao.getCustomers();
for (Customer customer : customers) {
JsonNode body = Unirest.get(EXTERNAL_TODOS_URL)
.queryString("userId", customer.getId())
.asJson()
.getBody();
JSONArray todos = body.getArray();
allTodos.put(customer, todos);
}
} catch (WarehouseException | UnirestException ex) {
System.err.printf("Problem during execution: %s%n", ex.getMessage());
}
allTodos.entrySet()
.stream()
.sorted((a, b) -> Integer.compare(b.getValue().length(), a.getValue().length()))
.limit(3L)
.collect(Collectors.toList())
.forEach(e -> System.out.printf("%s - %s (%s)%n",
e.getKey().getId(),
e.getKey().getName(),
e.getValue().length()));
}
示例13
private static Map<Integer, JSONObject> fetchCustomers() throws UnirestException {
return stream(Unirest.get(EXTERNAL_CUSTOMERS_URL)
.asJson()
.getBody()
.getArray()
.spliterator(), false)
.map(JSONObject.class::cast)
.collect(Collectors.toUnmodifiableMap(o -> o.getInt("id"), o -> o));
}
示例14
public static void main(String[] args) {
Map<Customer, JSONArray> allTodos = new HashMap<>();
try {
CustomerDao dao = new RestCustomerDao();
Collection<Customer> customers = dao.getCustomers();
for (Customer customer : customers) {
JsonNode body = Unirest.get(EXTERNAL_TODOS_URL)
.queryString("userId", customer.getId())
.asJson()
.getBody();
JSONArray todos = body.getArray();
allTodos.put(customer, todos);
}
} catch (WarehouseException | UnirestException ex) {
System.err.printf("Problem during execution: %s%n", ex.getMessage());
}
allTodos.entrySet()
.stream()
.sorted((a, b) -> Integer.compare(b.getValue().length(), a.getValue().length()))
.limit(3L)
.collect(Collectors.toList())
.forEach(e -> System.out.printf("%s - %s (%s)%n",
e.getKey().getId(),
e.getKey().getName(),
e.getValue().length()));
}
示例15
private static Map<Integer, JSONObject> fetchCustomers() throws UnirestException {
return stream(Unirest.get(EXTERNAL_CUSTOMERS_URL)
.asJson()
.getBody()
.getArray()
.spliterator(), false)
.map(JSONObject.class::cast)
.collect(Collectors.toUnmodifiableMap(o -> o.getInt("id"), o -> o));
}
示例16
@Override
public Collection<Product> getProducts() throws WarehouseException {
try {
return getArray(PRODUCTS_URL)
.map(JSONObject.class::cast)
.map(RestProductDao::toProduct)
.sorted(Comparator.comparing(Product::getId))
.collect(toList());
} catch (UnirestException ex) {
throw new WarehouseException("Problem while fetching products from API.", ex);
}
}
示例17
@Override
public Product getProduct(int id) throws WarehouseException {
try {
return toProduct(getObject(PRODUCTS_URL + "/" + id));
} catch (UnirestException ex) {
throw new WarehouseException(String.format("Problem while fetching product (%s) from API", id), ex);
}
}
示例18
@Override
public void addProduct(Product product) throws WarehouseException {
try {
postObject(PRODUCTS_URL, Map.of(
"name", product.getName(),
"price", product.getPrice()
));
} catch (UnirestException ex) {
throw new WarehouseException(String.format(
"Problem while creating product (%s, %s) from API", product.getName(), product.getPrice()), ex);
}
}
示例19
@Override
public Collection<Customer> getCustomers() throws WarehouseException {
try {
return getArray(CUSTOMERS_URL)
.map(RestCustomerDao::toCustomer)
.sorted(Comparator.comparing(Customer::getId))
.collect(toList());
} catch (UnirestException ex) {
throw new WarehouseException("Problem while fetching customers from API.", ex);
}
}
示例20
@Override
public Customer getCustomer(int id) throws WarehouseException {
try {
return toCustomer(getObject(CUSTOMERS_URL + "/" + id));
} catch (UnirestException ex) {
throw new WarehouseException(String.format("Problem while fetching customer (%s) from API", id), ex);
}
}
示例21
@Override
public void deleteCustomer(int id) throws WarehouseException {
try {
deleteObject(CUSTOMERS_URL + "/" + id);
} catch (UnirestException ex) {
throw new WarehouseException(String.format("Problem while deleting customer (%s) via API", id), ex);
}
}
示例22
protected Stream<JSONObject> getArray(String url) throws UnirestException {
HttpResponse<JsonNode> res = Unirest.get(url)
.asJson();
if (!res.isSuccess()) {
throw new UnirestException(res.getStatusText());
}
JSONArray array = res
.getBody()
.getArray();
return stream(array.spliterator(), false)
.map(JSONObject.class::cast);
}
示例23
protected void deleteObject(String url) throws UnirestException {
HttpResponse res = Unirest.delete(url)
.asEmpty();
if (!res.isSuccess()) {
throw new UnirestException(res.getStatusText());
}
}
示例24
public static void main(String[] args) {
Map<Customer, JSONArray> allTodos = new HashMap<>();
try {
CustomerDao dao = new RestCustomerDao();
Collection<Customer> customers = dao.getCustomers();
for (Customer customer : customers) {
JsonNode body = Unirest.get(EXTERNAL_TODOS_URL)
.queryString("userId", customer.getId())
.asJson()
.getBody();
JSONArray todos = body.getArray();
allTodos.put(customer, todos);
}
} catch (WarehouseException | UnirestException ex) {
System.err.printf("Problem during execution: %s%n", ex.getMessage());
}
allTodos.entrySet()
.stream()
.sorted((a, b) -> Integer.compare(b.getValue().length(), a.getValue().length()))
.limit(3L)
.collect(Collectors.toList())
.forEach(e -> System.out.printf("%s - %s (%s)%n",
e.getKey().getId(),
e.getKey().getName(),
e.getValue().length()));
}
示例25
private static Map<Integer, JSONObject> fetchCustomers() throws UnirestException {
return stream(Unirest.get(EXTERNAL_CUSTOMERS_URL)
.asJson()
.getBody()
.getArray()
.spliterator(), false)
.map(JSONObject.class::cast)
.collect(Collectors.toUnmodifiableMap(o -> o.getInt("id"), o -> o));
}
示例26
@Override
public Collection<Product> getProducts() throws WarehouseException {
try {
return getArray(PRODUCTS_URL)
.map(JSONObject.class::cast)
.map(RestProductDao::toProduct)
.sorted(Comparator.comparing(Product::getId))
.collect(toList());
} catch (UnirestException ex) {
throw new WarehouseException("Problem while fetching products from API.", ex);
}
}
示例27
@Override
public Product getProduct(int id) throws WarehouseException {
try {
return toProduct(getObject(PRODUCTS_URL + "/" + id));
} catch (UnirestException ex) {
throw new WarehouseException(String.format("Problem while fetching product (%s) from API", id), ex);
}
}
示例28
@Override
public void addProduct(Product product) throws WarehouseException {
try {
postObject(PRODUCTS_URL, Map.of(
"name", product.getName(),
"price", product.getPrice()
));
} catch (UnirestException ex) {
throw new WarehouseException(String.format(
"Problem while creating product (%s, %s) from API", product.getName(), product.getPrice()), ex);
}
}
示例29
@Override
public Collection<Customer> getCustomers() throws WarehouseException {
try {
return getArray(CUSTOMERS_URL)
.map(RestCustomerDao::toCustomer)
.sorted(Comparator.comparing(Customer::getId))
.collect(toList());
} catch (UnirestException ex) {
throw new WarehouseException("Problem while fetching customers from API.", ex);
}
}
示例30
@Override
public Customer getCustomer(int id) throws WarehouseException {
try {
return toCustomer(getObject(CUSTOMERS_URL + "/" + id));
} catch (UnirestException ex) {
throw new WarehouseException(String.format("Problem while fetching customer (%s) from API", id), ex);
}
}