下面列出了org.apache.http.client.methods.HttpPut#setEntity() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
private void installBootstrapExtension() throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
HttpPut put = new HttpPut("http://" + host + ":" + port
+ "/v1/config/resources/bootstrap?method=POST&post%3Abalanced=string%3F");
put.setEntity(new FileEntity(new File("src/test/resources/bootstrap.xqy"), "application/xquery"));
HttpResponse response = client.execute(put);
@SuppressWarnings("unused")
HttpEntity entity = response.getEntity();
System.out.println("Installed bootstrap extension. Response is "
+ response.toString());
}
/**
* Saves the specified matches.
*
* @param canvasMatches matches to save.
*
* @throws IOException
* if the request fails for any reason.
*/
public void saveMatches(final List<CanvasMatches> canvasMatches)
throws IOException {
if (canvasMatches.size() > 0) {
final String json = JsonUtils.MAPPER.writeValueAsString(canvasMatches);
final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
final URI uri = getUri(urls.getMatchesUrlString());
final String requestContext = "PUT " + uri;
final ResourceCreatedResponseHandler responseHandler = new ResourceCreatedResponseHandler(requestContext);
final HttpPut httpPut = new HttpPut(uri);
httpPut.setEntity(stringEntity);
LOG.info("saveMatches: submitting {} for {} pair(s)", requestContext, canvasMatches.size());
httpClient.execute(httpPut, responseHandler);
} else {
LOG.info("saveMatches: no matches to save");
}
}
/**
* Test action on a single plan item instance.
*/
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/oneManualActivationHumanTaskCase.cmmn" })
public void testDisablePlanItem() throws Exception {
CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").businessKey("myBusinessKey").start();
PlanItemInstance planItem = runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
String url = buildUrl(CmmnRestUrls.URL_PLAN_ITEM_INSTANCE, planItem.getId());
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new StringEntity("{\"action\": \"disable\"}"));
executeRequest(httpPut, HttpStatus.SC_NO_CONTENT);
planItem = runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertThat(planItem).isNull();
}
@Test
public void testCreateIfNonExistingUpdateInDocTrue() throws Exception {
Request request = new Request("http://localhost:" + getFirstListenPort() + update_test_create_if_non_existient_uri);
HttpPut httpPut = new HttpPut(request.getUri());
StringEntity entity = new StringEntity(update_test_create_if_non_existient_doc, ContentType.create("application/json"));
httpPut.setEntity(entity);
assertThat(doRest(httpPut).body, is(update_test_create_if_non_existing_response));
assertThat(getLog(), containsString("CREATE IF NON EXISTENT IS TRUE"));
}
/**
* Test executing an illegal action on an execution.
*/
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/ExecutionResourceTest.process-with-subprocess.bpmn20.xml" })
public void testIllegalExecutionAction() throws Exception {
Execution execution = runtimeService.startProcessInstanceByKey("processOne");
assertThat(execution).isNotNull();
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("action", "badaction");
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_EXECUTION, execution.getId()));
httpPut.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_BAD_REQUEST);
closeResponse(response);
}
public void updateTask(ServerConfig serverConfig, String taskId, JsonNode actionRequest) {
if (taskId == null) {
throw new IllegalArgumentException("Task id is required");
}
URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId));
HttpPut put = clientUtil.createPut(builder, serverConfig);
put.setEntity(clientUtil.createStringEntity(actionRequest));
clientUtil.executeRequestNoResponseBody(put, serverConfig, HttpStatus.SC_OK);
}
@Override
public HttpResponse Put(final String uri, final HttpEntity httpEntity, final String username,
final String password) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
final HttpPut put = new HttpPut(uri);
put.setEntity(httpEntity);
final HttpResponse response = client.execute(put);
return response;
}
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/repository/oneHumanTaskCase.cmmn" })
public void testUpdateLocalDateTimeProcessVariable() throws Exception {
LocalDateTime initial = LocalDateTime.parse("2020-01-18T12:32:45");
LocalDateTime tenDaysLater = initial.plusDays(10);
CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase")
.variables(Collections.singletonMap("overlappingVariable", (Object) "processValue")).start();
runtimeService.setVariable(caseInstance.getId(), "myVar", initial);
// Update variable
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("name", "myVar");
requestNode.put("value", "2020-01-28T12:32:45");
requestNode.put("type", "localDateTime");
HttpPut httpPut = new HttpPut(
SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_CASE_INSTANCE_VARIABLE, caseInstance.getId(), "myVar"));
httpPut.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
assertThatJson(runtimeService.getVariable(caseInstance.getId(), "myVar")).isEqualTo(tenDaysLater);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertThat(responseNode).isNotNull();
assertThatJson(responseNode)
.when(Option.IGNORING_EXTRA_FIELDS)
.isEqualTo("{"
+ " value: '2020-01-28T12:32:45'"
+ "}");
}
/**
* Invokes the Render Web Service using specified parameters and
* writes the resulting image to the specified output file.
*
* @param renderParameters render parameters.
* @param outputFile result image file.
* @param outputFormat format of result image (e.g. 'jpeg' or 'png').
*
* @throws IOException
* if the render request fails for any reason.
*/
public void renderToFile(final RenderParameters renderParameters,
final File outputFile,
final String outputFormat)
throws IOException {
LOG.info("renderToFile: entry, renderParameters={}, outputFile={}, outputFormat={}",
renderParameters, outputFile, outputFormat);
if (outputFile.exists()) {
if (! outputFile.canWrite()) {
throw new IOException("output file " + outputFile.getAbsolutePath() + " cannot be overwritten");
}
} else {
File parentFile = outputFile.getParentFile();
while (parentFile != null) {
if (parentFile.exists()) {
if (! parentFile.canWrite()) {
throw new IOException("output file cannot be written to parent directory " +
parentFile.getAbsolutePath());
}
break;
}
parentFile = parentFile.getParentFile();
}
}
final String json = renderParameters.toJson();
final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
final URI uri = getRenderUriForFormat(outputFormat);
final FileResponseHandler responseHandler = new FileResponseHandler("PUT " + uri,
outputFile);
final HttpPut httpPut = new HttpPut(uri);
httpPut.setEntity(stringEntity);
httpClient.execute(httpPut, responseHandler);
LOG.info("renderToFile: exit, wrote image to {}", outputFile.getAbsolutePath());
}
/**
* Test suspending a single process instance.
*/
@Deployment(resources = { "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testActivateProcessInstance() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");
runtimeService.suspendProcessInstanceById(processInstance.getId());
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("action", "activate");
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
httpPut.setEntity(new StringEntity(requestNode.toString()));
CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
// Check engine id instance is suspended
assertEquals(1, runtimeService.createProcessInstanceQuery().active().processInstanceId(processInstance.getId()).count());
// Check resulting instance is suspended
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertNotNull(responseNode);
assertEquals(processInstance.getId(), responseNode.get("id").textValue());
assertFalse(responseNode.get("suspended").booleanValue());
// Activating again should result in conflict
httpPut.setEntity(new StringEntity(requestNode.toString()));
closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI url, InputStream data) {
switch (method) {
case GET:
return new HttpGet(url);
case POST:
HttpPost post = new HttpPost(url);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(url);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(url);
case PATCH:
HttpPatch patch = new HttpPatch(url);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
}
throw new IllegalArgumentException("Refusing to proxy " + method + " " + url + ": Unsupported method");
}
@Test
public void testUpdateStory() throws Exception {
StoryObject story = mASTS.getStories().get(0);
// initial request data
JSONObject storyJson = new JSONObject();
storyJson.put("id", story.getId()).put("name", "顆顆").put("notes", "崩潰")
.put("how_to_demo", "做不完").put("importance", 99)
.put("value", 15).put("estimate", 21).put("status", 0)
.put("sprint_id", -1).put("tags", "");
String URL = String.format(API_URL, mProjectName, "update", mUsername, mPassword);
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream(storyJson.toString().getBytes()));
entity.setContentEncoding("utf-8");
HttpPut httpPut = new HttpPut(URL);
httpPut.setEntity(entity);
String result = EntityUtils.toString(mHttpClient.execute(httpPut).getEntity(), StandardCharsets.UTF_8);
JSONObject response = new JSONObject(result);
assertEquals(storyJson.getLong("id"), response.getLong("id"));
assertEquals(storyJson.getString("name"), response.getString("name"));
assertEquals(storyJson.getString("notes"), response.getString("notes"));
assertEquals(storyJson.getString("how_to_demo"), response.getString("how_to_demo"));
assertEquals(storyJson.getInt("importance"), response.getInt("importance"));
assertEquals(storyJson.getInt("value"), response.getInt("value"));
assertEquals(storyJson.getInt("estimate"), response.getInt("estimate"));
assertEquals(storyJson.getInt("status"), response.getInt("status"));
assertEquals(storyJson.getLong("sprint_id"), response.getLong("sprint_id"));
assertEquals(9, response.getJSONArray("histories").length());
assertEquals(0, response.getJSONArray("tags").length());
}
@Override
public void setPutEntity(String xmlstr, HttpPut httpput) throws UnsupportedEncodingException {
StringEntity input = new StringEntity(xmlstr);
if (xmlstr != null && !xmlstr.isEmpty()) {
input.setContentType("application/xml");
}
httpput.setEntity(input);
}
@Test
public void testUpdatePicture() throws Exception {
User savedUser = null;
try {
User newUser = identityService.newUser("testuser");
newUser.setFirstName("Fred");
newUser.setLastName("McDonald");
newUser.setEmail("[email protected]");
identityService.saveUser(newUser);
savedUser = newUser;
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER_PICTURE, newUser.getId()));
httpPut.setEntity(HttpMultipartHelper
.getMultiPartEntity("myPicture.png", "image/png", new ByteArrayInputStream("this is the picture raw byte stream".getBytes()), null));
closeResponse(executeBinaryRequest(httpPut, HttpStatus.SC_NO_CONTENT));
Picture picture = identityService.getUserPicture(newUser.getId());
assertThat(picture).isNotNull();
assertThat(picture.getMimeType()).isEqualTo("image/png");
assertThat(new String(picture.getBytes())).isEqualTo("this is the picture raw byte stream");
} finally {
// Delete user after test passes or fails
if (savedUser != null) {
identityService.deleteUser(savedUser.getId());
}
}
}
/**
* Test updating an unexisting user.
*/
@Test
public void testUpdateUnexistingUser() throws Exception {
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, "unexisting"));
httpPut.setEntity(new StringEntity(objectMapper.createObjectNode().toString()));
closeResponse(executeRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}
private static HttpPut putForm(String url, JSONObject data) {
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader(CONNECTION, KEEP_ALIVE);
httpPut.setHeader(CONTENT_TYPE, APPLICATION_JSON);
StringEntity entity = new StringEntity(data.toString(), UTF8);//解决中文乱码问题
httpPut.setEntity(entity);
return httpPut;
}
void putFlagData(FlagsTarget target, FlagData flagData) throws FlagsException, UncheckedIOException {
HttpPut request = new HttpPut(createUri(target, "/data/" + flagData.id().toString(), List.of()));
request.setEntity(jsonContent(flagData.serializeToJson()));
executeRequest(request, response -> {
verifySuccess(response, flagData.id());
return null;
});
}
@Override
public void run() {
try {
if (sugarSyncAccount.loginsuccessful) {
host = sugarSyncAccount.username + " | SugarSync.com";
} else {
host = "SugarSync.com";
uploadInvalid();
return;
}
uploadInitialising();
getUserInfo();
String ext = FileUtils.getFileExtension(file);
String CREATE_FILE_REQUEST = String.format(CREATE_FILE_REQUEST_TEMPLATE, file.getName(), ext + " file");
NULogger.getLogger().info("now creating file request............");
postData(CREATE_FILE_REQUEST, upload_folder_url);
HttpPut httpput = new HttpPut(SugarSync_File_Upload_URL);
httpput.setHeader("Authorization", sugarSyncAccount.getAuth_token());
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("", createMonitoredFileBody());
httpput.setEntity(reqEntity);
uploading();
NULogger.getLogger().info("Now uploading your file into sugarsync........ Please wait......................");
NULogger.getLogger().log(Level.INFO, "Now executing.......{0}", httpput.getRequestLine());
httpResponse = httpclient.execute(httpput);
HttpEntity entity = httpResponse.getEntity();
NULogger.getLogger().info(httpResponse.getStatusLine().toString());
if (httpResponse.getStatusLine().getStatusCode() == 204) {
NULogger.getLogger().info("File uploaded successfully :)");
uploadFinished();
} else {
throw new Exception("There might be problem with your internet connection or server error. Please try again some after time :(");
}
} catch (Exception e) {
Logger.getLogger(SugarSync.class.getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}
public void testUpdateUnexistingModel() throws Exception {
HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, "unexisting"));
httpPut.setEntity(new StringEntity(objectMapper.createObjectNode().toString()));
closeResponse(executeRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}