com.mashape.unirest.http.HttpMethod Java Examples

The following examples show how to use com.mashape.unirest.http.HttpMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestAction.java    From cognitivej with Apache License 2.0 6 votes vote down vote up
private T doWork() {
    try {
        setupErrorHandlers();
        WorkingContext workingContext = workingContext();
        HttpRequest builtRequest = buildUnirest(workingContext)
                .queryString(workingContext.getQueryParams())
                .headers(workingContext.getHeaders()).header("Ocp-Apim-Subscription-Key", cognitiveContext.subscriptionKey);
        if (!workingContext.getHttpMethod().equals(HttpMethod.GET) && workingContext().getPayload().size() > 0) {
            buildBody((HttpRequestWithBody) builtRequest);
        }
        HttpResponse response;
        if (typedResponse() == InputStream.class)
            response = builtRequest.asBinary();
        else
            response = builtRequest.asString();

        checkForError(response);
        return postProcess(typeResponse(response.getBody()));
    } catch (UnirestException | IOException e) {
        throw new CognitiveException(e);
    }
}
 
Example #2
Source File: AddFaceToFaceListAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.addQueryParameter("userData", userData)
            .setPath("face/v1.0/facelists/${faceListId}/persistedFaces").addPathVariable("faceListId", faceListId)
            .addQueryParameter("userData", userData)
            .httpMethod(HttpMethod.POST);
    if (isNotEmpty(targetFace))
        workingContext.addQueryParameter("targetFace", targetFace);
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #3
Source File: TagImageAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("vision/v1.0/tag")
            .httpMethod(HttpMethod.POST);

    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #4
Source File: DescribeImageAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("vision/v1.0/describe")
            .httpMethod(HttpMethod.POST);
    workingContext().addQueryParameter("maxCandidates", String.valueOf(maxCandidates));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #5
Source File: UpdateFaceToPersonAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext() {
    workingContext.addPayload("userData", userData)
            .setPath("face/v1.0/persongroups/${personGroupId}/persons/${personId}/persistedFaces/${persistedFaceId}")
            .addPathVariable("personGroupId", personGroupId)
            .addPathVariable("personId", personId)
            .addPathVariable("persistedFaceId", persistedFaceId)
            .httpMethod(HttpMethod.PATCH);

}
 
Example #6
Source File: RecognizeDomainSpecificContentInImageAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("vision/v1.0/models/${models}/analyze")
            .httpMethod(HttpMethod.POST);

    if (Utils.isNotEmpty(models))
        workingContext().addPathVariable("models", StringUtils.join(models, ','));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #7
Source File: AddFaceToPersonAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object payload) {
    workingContext.addQueryParameter("userData", userData)
            .setPath("face/v1.0/persongroups/${personGroupId}/persons/${personId}/persistedFaces").addPathVariable("personGroupId", personGroupId)
            .addPathVariable("personId", personId)
            .httpMethod(HttpMethod.POST);
    if (payload instanceof String)
        workingContext.addPayload("url", String.valueOf(payload));
    if (payload instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, payload);

}
 
Example #8
Source File: FindSimilarFacesAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext() {
    workingContext.setPath("face/v1.0/findsimilars")
            .httpMethod(HttpMethod.POST).addPayload("faceId", faceId).addPayload("maxNumOfCandidatesReturned", maxNumOfCandidates);
    if (Utils.isNotEmpty(faceIds))
        workingContext().addPayload("faceIds", faceIds);
    else
        workingContext().addPayload("faceListId", faceListId);
}
 
Example #9
Source File: GetThumbnailAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("vision/v1.0/generateThumbnail")
            .httpMethod(HttpMethod.POST);


    workingContext().addQueryParameter("width", String.valueOf(width));
    workingContext().addQueryParameter("height", String.valueOf(height));
    workingContext().addQueryParameter("smartCropping", String.valueOf(smartCropping));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #10
Source File: OCROnImageAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("vision/v1.0/ocr")
            .httpMethod(HttpMethod.POST);

    if (Utils.isNotBlank(language))
        workingContext().addQueryParameter("language", language);
    workingContext().addQueryParameter("detectOrientation", String.valueOf(detectOrientation));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #11
Source File: DetectFaceAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("face/v1.0/detect").addQueryParameter("returnFaceId", String.valueOf(returnFaceId)).
            addQueryParameter("returnFaceId", String.valueOf(returnFaceId)).addQueryParameter("returnFaceLandmarks", String.valueOf(returnFaceLandmarks))
            .httpMethod(HttpMethod.POST);
    if (returnFaceAttributes != null)
        workingContext().addQueryParameter("returnFaceAttributes", StringUtils.join(returnFaceAttributes, ','));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #12
Source File: AnalyzeImageAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("vision/v1.0/analyze")
            .httpMethod(HttpMethod.POST);
    if (Utils.isNotEmpty(visualFeatures))
        workingContext().addQueryParameter("visualFeatures", StringUtils.join(visualFeatures, ','));
    if (Utils.isNotEmpty(visualFeatures))
        workingContext().addQueryParameter("details", StringUtils.join(domainSpecificDetails, ','));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #13
Source File: EmotionRecognitionAction.java    From cognitivej with Apache License 2.0 5 votes vote down vote up
private void buildContext(Object image) {
    workingContext.setPath("emotion/v1.0/recognize")
            .httpMethod(HttpMethod.POST);
    if (faceRectangle != null)
        workingContext().addQueryParameter("faceRectangle", String.format("%s;%s;%s;%s", faceRectangle.left, faceRectangle.top, faceRectangle.width, faceRectangle.height));
    if (image instanceof String)
        workingContext.addPayload("url", String.valueOf(image));
    if (image instanceof InputStream)
        workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image);
}
 
Example #14
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public JsonObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields,
		String jsonReturnedValue) throws Exception {
	JsonObject json = this.commonRest(method, path, body, status);
	JsonObject jsonObjExpected = null;
	jsonReturnedValue.replaceAll("'", "\"");
	try {
		jsonObjExpected = JsonParser.parseString(jsonReturnedValue).getAsJsonObject();
	} catch (JsonSyntaxException e1) {
		throw new Exception("Expected json element is a string without a JSON format: " + jsonReturnedValue);
	}

	if (exactReturnedFields) {
		if (jsonObjExpected.size() != json.size()) {
			throw new Exception(
					"Error in number of keys in JSON response to POST (" + json.toString() + ")" + path);
		}
	}
	for (String key : jsonObjExpected.keySet()) {
		Class<?> c1 = jsonObjExpected.get(key).getClass();
		Class<?> c2 = json.get(key).getClass();

		c1 = unifyNumberType(c1);
		c2 = unifyNumberType(c2);

		if (!c1.equals(c2)) {
			throw new Exception("Wrong class of property " + key);
		}
	}
	return json;
}
 
Example #15
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 5 votes vote down vote up
private JsonObject commonRest(HttpMethod method, String path, String body, int status) throws Exception {
	HttpResponse<?> jsonResponse = null;
	JsonObject json = null;
	path = openviduUrl + (path.startsWith("/") ? path : ("/" + path));

	HttpRequest request = null;
	if (body != null && !body.isEmpty()) {
		switch (method) {
		case POST:
			request = Unirest.post(path);
			break;
		case PUT:
			request = Unirest.put(path);
			break;
		case PATCH:
		default:
			request = Unirest.patch(path);
			break;
		}
		((HttpRequestWithBody) request).header("Content-Type", "application/json").body(body.replaceAll("'", "\""));
	} else {
		switch (method) {
		case GET:
			request = Unirest.get(path);
			request.header("Content-Type", "application/x-www-form-urlencoded");
			break;
		case POST:
			request = Unirest.post(path);
			break;
		case DELETE:
			request = Unirest.delete(path);
			request.header("Content-Type", "application/x-www-form-urlencoded");
			break;
		case PUT:
			request = Unirest.put(path);
		default:
			break;
		}
	}

	request = request.header("Authorization", this.headerAuth);
	try {
		jsonResponse = request.asJson();
		if (jsonResponse.getBody() != null) {
			jsonResponse.getBody();
			json = JsonParser.parseString(((JsonNode) jsonResponse.getBody()).getObject().toString())
					.getAsJsonObject();
		}
	} catch (UnirestException e) {
		try {
			if (e.getCause().getCause().getCause() instanceof org.json.JSONException) {
				try {
					jsonResponse = request.asString();
				} catch (UnirestException e1) {
					throw new Exception("Error sending request to " + path + ": " + e.getMessage());
				}
			} else {
				throw new Exception("Error sending request to " + path + ": " + e.getMessage());
			}
		} catch (NullPointerException e2) {
			throw new Exception("Error sending request to " + path + ": " + e.getMessage());
		}
	}

	if (jsonResponse.getStatus() == 500) {
		log.error("Internal Server Error: {}", jsonResponse.getBody().toString());
	}

	if (status != jsonResponse.getStatus()) {
		System.err.println(jsonResponse.getBody().toString());
		throw new Exception(path + " expected to return status " + status + " but got " + jsonResponse.getStatus());
	}

	return json;
}
 
Example #16
Source File: HttpRequest.java    From unirest-android with MIT License 5 votes vote down vote up
public HttpRequest(HttpMethod method, String url) {
	this.httpMethod = method;
	try {
		this.url = parseUrl(url).toString();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	
	super.httpRequest = this;
}
 
Example #17
Source File: WorkingContext.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
@NotNull
public HttpMethod getHttpMethod() {
    return httpMethod;
}
 
Example #18
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 4 votes vote down vote up
public JsonObject rest(HttpMethod method, String path, int status) throws Exception {
	return this.commonRest(method, path, null, status);
}
 
Example #19
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 4 votes vote down vote up
public JsonObject rest(HttpMethod method, String path, String body, int status) throws Exception {
	return this.commonRest(method, path, body, status);
}
 
Example #20
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 4 votes vote down vote up
public JsonObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields,
		Map<String, ?> jsonResponse) throws Exception {
	JsonObject json = this.commonRest(method, path, body, status);

	if (exactReturnedFields) {
		if (jsonResponse.size() != json.size())
			throw new Exception("Error in number of keys in JSON response to POST " + path);
	}

	for (Map.Entry<String, ?> entry : jsonResponse.entrySet()) {
		Object value = entry.getValue();

		if (value instanceof String) {
			try {
				JsonObject jsonObjExpected = JsonParser.parseString((String) value).getAsJsonObject();
				JsonObject jsonObjActual = json.get(entry.getKey()).getAsJsonObject();
				// COMPARE

			} catch (JsonSyntaxException e1) {
				try {
					JsonArray jsonArrayExpected = JsonParser.parseString((String) value).getAsJsonArray();
					JsonArray jsonArrayActual = json.get(entry.getKey()).getAsJsonArray();
					// COMPARE

				} catch (JsonSyntaxException e2) {
					if (((String) value) != json.get(entry.getKey()).getAsString()) {
						throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: "
								+ value + ". Actual: " + json.get(entry.getKey()).getAsString());
					}
				}
			}
		} else if (value instanceof Integer) {
			if (((int) value) != json.get(entry.getKey()).getAsInt()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsInt());
			}
		} else if (value instanceof Long) {
			if (((long) value) != json.get(entry.getKey()).getAsLong()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsLong());
			}
		} else if (value instanceof Double) {
			if (((double) value) != json.get(entry.getKey()).getAsDouble()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsDouble());
			}
		} else if (value instanceof Boolean) {
			if (((boolean) value) != json.get(entry.getKey()).getAsBoolean()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsBoolean());
			}
		} else if (value instanceof JSONArray || value instanceof JsonArray) {
			JsonParser.parseString(entry.getValue().toString()).getAsJsonArray();
		} else if (value instanceof JSONObject || value instanceof JsonObject) {
			JsonParser.parseString(entry.getValue().toString()).getAsJsonObject();
		} else {
			throw new Exception("JSON response field cannot be parsed: " + entry.toString());
		}
	}
	return json;
}
 
Example #21
Source File: ListDomainSpecificModelsAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext() {
    workingContext.setPath("vision/v1.0/models")
            .httpMethod(HttpMethod.GET);
}
 
Example #22
Source File: GetRequest.java    From unirest-android with MIT License 4 votes vote down vote up
public GetRequest(HttpMethod method, String url) {
	super(method, url);
}
 
Example #23
Source File: HttpRequest.java    From unirest-android with MIT License 4 votes vote down vote up
public HttpMethod getHttpMethod() {
	return httpMethod;
}
 
Example #24
Source File: DeleteFaceListAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext(String id) {
    workingContext.setPath("face/v1.0/facelists/${id}").addPathVariable("id", id)
            .httpMethod(HttpMethod.DELETE);
}
 
Example #25
Source File: HttpRequestWithBody.java    From unirest-android with MIT License 4 votes vote down vote up
public HttpRequestWithBody(HttpMethod method, String url) {
	super(method, url);
}
 
Example #26
Source File: GetPersonAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext(String id) {
    workingContext.setPath("face/v1.0/persongroups/${personGroupId}/persons/${personId}")
            .addPathVariable("personGroupId", id).addPathVariable("personId", personId)
            .httpMethod(HttpMethod.GET);
}
 
Example #27
Source File: DeletePersonGroupAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext(String id) {
    workingContext.setPath("face/v1.0/persongroups/${id}").addPathVariable("id", id)
            .httpMethod(HttpMethod.DELETE);
}
 
Example #28
Source File: CreateFaceListAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext() {
    workingContext.addPayload("name", name).addPayload("userData", userData)
            .setPath("face/v1.0/facelists/${faceListId}").addPathVariable("faceListId", faceListId)
            .httpMethod(HttpMethod.PUT);
}
 
Example #29
Source File: GetFaceListAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext(String faceListId) {
    workingContext.setPath("face/v1.0/facelists/${faceListId}").addPathVariable("faceListId", faceListId)
            .httpMethod(HttpMethod.GET);
}
 
Example #30
Source File: ListFaceListsAction.java    From cognitivej with Apache License 2.0 4 votes vote down vote up
private void buildContext() {
    workingContext.setPath("face/v1.0/facelists")
            .httpMethod(HttpMethod.GET);
}