Form form = new Form(); form.add("x", "foo"); form.add("y", "bar"); ClientResource resource = new ClientResource("http://localhost:8080/someresource"); Response response = resource.post(form.getWebRepresentation()); if (response.getStatus().isSuccess()) { System.out.println("Success! " + response.getStatus()); System.out.println(response.getEntity().getText()); } else { System.out.println("ERROR! " + response.getStatus()); System.out.println(response.getEntity().getText()); }
JSONObject jsonObj = new JSONObject(); jsonObj.put("host", "..."); ClientResource cr = new Client("http://myownHost/resource/1"); cr.post(new JsonRepresentation(jsonObject); // In the case of form // Form form = new Form (); // form.set("host", "..."); // cr.post(form);
// Create the client resource ClientResource resource = new ClientResource("http://restlet.org"); // Write the response entity on the console resource.post(yourJsonObject).write(System.out);
ClientResource cr = new ClientResource("http://..."); SONObject jo = new JSONObject(); jo.add("entryOne", "..."); jo.add("entryTow", "..."); cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
ClientResource cr = new ClientResource("http://..."); JSONObject obj = new JSONObject(); obj.put("activity", "my value"); (...) cr.post(new JsonRepresentation(obj));
final String username = "username"; final String password = "password"; // Create your own authenticator Authenticator a = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication( username, password.toCharArray())); } }; // Sets the default Authenticator Authenticator.setDefault(a); ClientResource cr = new ClientResource("http://..."); cr.post(...);
message.put("password", "pass"); cr.post(message, MediaType.APPLICATION_JSON);
ClientResource clientResource = new ClientResource(url); Request request = new Request(Method.POST, url); clientResource.setRequest(request); Form form = new Form(); form.set("foo", "barValue"); org.restlet.representation.Representation response = clientResource.post(form, MediaType.APPLICATION_JSON); Representation responseEntity = clientResource.getResponseEntity(); JsonRepresentation jsonRepresentation = new JsonRepresentation(responseEntity); JSONObject jsonObject = jsonRepresentation.getJsonObject(); String[] names = JSONObject.getNames(jsonObject); if (jsonObject.has("errorString")) { String error = jsonObject.optString("errorString"); }
/** * Posts an object entity. Automatically serializes the object using the * {@link org.restlet.service.ConverterService}. * * @param entity * The object entity to post. * @return The optional result entity. * @throws ResourceException * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP * POST method</a> */ public Representation post(Object entity) throws ResourceException { try { return post(toRepresentation(entity)); } catch (IOException e) { throw new ResourceException(e); } }
/** * Sends registration post request. * * @param user user entity for registration * @param dryRun do not register the user, just check if it is possible * @return ClientResource result */ protected ClientResource sendRegistrationRequest(User user, Boolean dryRun) { ClientResource clientResource = createClientResource(regUrl, true); addCredentialsIfAny(clientResource); if (dryRun) { addHeaderAttribute(clientResource, "dryRun", "true"); } writeRequestInfoToLog(clientResource); try { clientResource.post(user); } catch (ResourceException e) { logger.warn("Poulpe registration request error: {}", e.getStatus()); } return clientResource; }
@Override public <T> String encodeMetadata(MetadataDataType metadataDataType, T instance) throws ServiceException { String encodedRawValue; ClientResource service = createClient(MetadataEndpoints.encodeMetadata(metadataDataType)); try { Representation result = service.post(new StringRepresentation(instance.toString())); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); if (service.getStatus().equals(Status.SUCCESS_OK)) { encodedRawValue = jsonResult.getString(Field.RAW_VALUE_FIELD); } else { LOGGER.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); ResponseEntity response = JsonUtil.fromJson(jsonResult, ResponseEntity.class); throw new ServiceException(response); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected Exception", e); throw new ServiceException(e); } return encodedRawValue; }
@Override public boolean changePassword(String oldPassword, String newPassword) throws ServiceException { boolean wasChanged; ClientResource service = createClient(AccountEndpoints.changeMyPassword()); try { JSONObject jsonObject = new JSONObject() .put(Field.OLD_PASSWORD_FIELD, oldPassword) .put(Field.NEW_PASSWORD_FIELD, newPassword); Representation result = service.post(new JsonRepresentation(jsonObject)); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); ResponseEntity responseEntity = JsonUtil.fromJson(jsonResult, ResponseEntity.class); if (!service.getStatus().equals(Status.SUCCESS_OK)) { LOGGER.error("Unexpected HTTP status code returned: " + service.getStatus().getCode()); throw new ServiceException(responseEntity); } else { LOGGER.debug(responseEntity.getMessage()); wasChanged = (responseEntity.getCode() == Result.OK.getCode()); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected exception", e); throw new ServiceException(e); } return wasChanged; }
@Override public void sendPasswordResetEmail(String emailAddress) throws ServiceException { ClientResource service = createClient(AccountEndpoints.resetMyPassword()); try { Representation result = service .post(new StringRepresentation(emailAddress, MediaType.TEXT_PLAIN), MediaType.APPLICATION_JSON); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); ResponseEntity responseEntity = JsonUtil.fromJson(jsonResult, ResponseEntity.class); if (!service.getStatus().equals(Status.SUCCESS_OK)) { LOGGER.error("Unexpected HTTP status code returned: " + service.getStatus().getCode()); throw new ServiceException(responseEntity); } else { LOGGER.debug(responseEntity.getMessage()); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected exception", e); throw new ServiceException(e); } }
@Override public JSONObject decodeMetadata(MetadataDataType metadataDataType, JSONObject jsonObject) throws ServiceException { JSONObject jsonResult; ClientResource service = createClient(MetadataEndpoints.decodeMetadata(metadataDataType)); try { Representation result = service.post(new JsonRepresentation(jsonObject)); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); jsonResult = jsonRepresentation.getJsonObject(); if (service.getStatus().equals(Status.SUCCESS_OK)) { return jsonResult; } else { LOGGER.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); ResponseEntity response = JsonUtil.fromJson(jsonResult, ResponseEntity.class); throw new ServiceException(response); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected Exception", e); throw new ServiceException(e); } }
@Override public ResponseEntity uploadOctetStream(String urn, java.io.File file, MediaType mediaType) throws ServiceException { ResponseEntity response; FileRepresentation fileRepresentation = new FileRepresentation(file, mediaType); fileRepresentation.setMediaType(MediaType.APPLICATION_OCTET_STREAM); ClientResource service = createClient(FileEndpoints.uploadContentsAsOctetStream(urn)); service.accept(MediaType.APPLICATION_JSON); try { Representation result = service.post(fileRepresentation); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); response = JsonUtil.fromJson(jsonResult, ResponseEntity.class); if (service.getStatus().equals(Status.SUCCESS_OK)) { LOGGER.info("Successfully uploaded file to path {}", FileEndpoints.uploadContentsAsMultipart(urn)); } else { LOGGER.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); throw new ServiceException(response); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected Exception", e); throw new ServiceException(e); } return response; }
Representation r = itemsResource.post(getRepresentation(item)); itemResource = new ClientResource(r.getLocationRef()); } catch (ResourceException e) {
public class PMCResourceMain { public static void main(String[] args) { // take into account the context-root, if exists, and path to your REST service ClientResource resource = new ClientResource("http://<host>:<port>"); MyPojo myPojo = new MyPojo(); myPojo.setCampaingID(1); myPojo.setClientID(1); myPojo.setPmapID(1); myPojo.setWard("1-Bedded (Private)"); myPojo.setAge(20); myPojo.setAttr1("EXA1(A)"); myPojo.setAttr2("EO"); myPojo.setAttr3("11/02/2012"); myPojo.setAttr4("SIN"); myPojo.setAttr5("N"); myPojo.setAttr6("Y"); try { resource.post(myPojo, MediaType.APPLICATION_JSON).write(System.out); } catch (ResourceException | IOException e) { e.printStackTrace(); } } }
/** * Tests that an error occurs when trying to create a user without submitting a form */ @Test public void testErrorUpdateUserPostNoContent() throws Exception { try { final ClientResource creationClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_UPDATE_USER_PATH, OasProps.PROP_UPDATE_USER_PATH))); final FormDataSet form = new FormDataSet(); form.setMultipart(false); form.setMediaType(MediaType.APPLICATION_WWW_FORM); creationClientResource.post(form); Assert.fail("Did not receive expected exception"); } catch(final ResourceException rex) { Assert.assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, rex.getStatus()); } }
/** * Tests that an error occurs when trying to get the create user resource while unauthenticated. */ @Test public void testErrorDeleteUserGetNotAuthenticated() throws Exception { try { final ClientResource deletionClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_DELETE_USER_PATH, OasProps.DEF_DELETE_USER_PATH))); final FormDataSet form = new FormDataSet(); form.setMultipart(false); form.setMediaType(MediaType.APPLICATION_WWW_FORM); form.add("username", "anotherUser"); deletionClientResource.post(form); Assert.fail("Did not receive expected exception"); } catch(final ResourceException rex) { Assert.assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, rex.getStatus()); } }
/** * Tests that an error occurs when trying to get the create user resource while unauthenticated. */ @Test public void testErrorUpdateUserPostNotAuthenticated() throws Exception { try { final ClientResource creationClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_UPDATE_USER_PATH, OasProps.PROP_UPDATE_USER_PATH))); final FormDataSet form = new FormDataSet(); form.setMultipart(false); form.setMediaType(MediaType.APPLICATION_WWW_FORM); form.getEntries().add(new FormData("username", "testNewUser")); form.getEntries().add(new FormData("password", "testNewPassword")); form.getEntries().add(new FormData("email", "test@email.com")); creationClientResource.post(form); Assert.fail("Did not receive expected exception"); } catch(final ResourceException rex) { Assert.assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, rex.getStatus()); } }