Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

attachment support #13

Open
kleinmantara opened this issue Apr 5, 2022 · 0 comments
Open

attachment support #13

kleinmantara opened this issue Apr 5, 2022 · 0 comments

Comments

@kleinmantara
Copy link

Code example for the PushoverRestClient class with the dependencies to httpmime.

	private static final ContentType plainUTF = ContentType.create("text/plain", MIME.UTF8_CHARSET);
	
	public Status pushMessage(PushoverMessage msg) throws PushoverException {
		final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addTextBody("token", msg.getApiToken(), plainUTF);
		builder.addTextBody("user", msg.getUserId(), plainUTF);
		builder.addTextBody("message", msg.getMessage(), plainUTF);

		addBodyIfNotNull(builder, "title", msg.getTitle());

		addBodyIfNotNull(builder, "url", msg.getUrl());
		addBodyIfNotNull(builder, "url_title", msg.getTitle());

		addBodyIfNotNull(builder, "device", msg.getDevice());
		addBodyIfNotNull(builder, "timestamp", "" + msg.getTimestamp());
		addBodyIfNotNull(builder, "sound", msg.getSound());
		addBodyIfNotNull(builder, "html", msg.isHtml() ? "1" : "0");

		if (!MessagePriority.NORMAL.equals(msg.getPriority())) {
			addBodyIfNotNull(builder, "priority", "" + msg.getPriority());
		}

		if (msg.getFile != null) {
			builder.addBinaryBody("attachment", msg.getFile().getStream(), msg.getFile().getContentType(),
					msg.getFile().getName());
		}

		HttpEntity multipart = builder.build();
		HttpPost post = new HttpPost(PUSH_MESSAGE_URL);
		post.setEntity(multipart);

		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpResponse response = httpClient.execute(post);
			return PushoverResponseFactory.createStatus(response);
		} catch (Exception e) {
			throw new PushoverException(e.getMessage(), e.getCause());
		}
	}
	private void addBodyIfNotNull(MultipartEntityBuilder builder, String name, String value) {
		builder.addTextBody(name, value, plainUTF);
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant