本文整理匯總了Java中org.apache.http.entity.mime.content.ContentBody類的典型用法代碼示例。如果您正苦於以下問題:Java ContentBody類的具體用法?Java ContentBody怎麽用?Java ContentBody使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ContentBody類屬於org.apache.http.entity.mime.content包,在下文中一共展示了ContentBody類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: fileUpload
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
private static void fileUpload() throws Exception {
file = new File("/home/vigneshwaran/VIGNESH/dinesh.txt");
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("ssd", new StringBody(ssd));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into slingfile.com");
HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
}
示例2: notifyOnSlack
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
/**
* This method is used to send slack notification.
*
* @return boolean slack response
* @throws IOException
*/
private void notifyOnSlack(Employee employee, Visitor visitor, SlackChannel channel, String locationName) throws IOException {
Map<String,ContentBody> attachment = createAttachment(imageService.getBaseDirPathAsStr(), visitor.getVisitorPic(), imageService.getDefaultImageFile());
Map<String, String> param = null;
if (Objects.nonNull(employee)) {
String slackMessage = createMessage(configurationService.getSlackConfiguration().getMessage(),
visitor, employee, locationName);
param = buildSlackRequestParam(employee.getSlackId(), slackMessage, configurationService.getSlackConfiguration().getToken());
}
else {
String channelMessage = messageForChannel(configurationService.getSlackConfiguration().
getChannelMessage(), visitor, channel, locationName);
param = buildSlackRequestParam(channel.getChannelId(), channelMessage, configurationService.getSlackConfiguration().getToken());
}
slackService.sendMessage(param, attachment);
}
示例3: composeMultiPartFormRequest
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters, final Map<String, ContentBody> files) {
HttpPost request = new HttpPost(uri);
MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
Charset utf8 = Charset.forName("UTF-8");
for(Parameter param : parameters)
if(param.isSingleValue())
multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8));
else
for(String value : param.getValues())
multiPartEntity.addPart(param.getName(), new StringBody(value, utf8));
} catch (UnsupportedEncodingException e) {
throw MechanizeExceptionFactory.newException(e);
}
List<String> fileNames = new ArrayList<String>(files.keySet());
Collections.sort(fileNames);
for(String name : fileNames) {
ContentBody contentBody = files.get(name);
multiPartEntity.addPart(name, contentBody);
}
request.setEntity(multiPartEntity);
return request;
}
示例4: uploadDatabase
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
private void uploadDatabase() throws Exception {
tempDB = File.createTempFile("temp_", ".sqlite", serviceModule.getDirectoryPath());
databaseManager.mergeRecord().dumpDatabaseTo(tempDB);
// check if database is empty
if (databaseManager.mergeRecord().isEmpty(tempDB)) {
FLog.d("database is empty");
return;
}
HashMap<String, ContentBody> extraParts = new HashMap<String, ContentBody>();
extraParts.put("user", new StringBody(databaseManager.getUserId()));
if (!uploadFile("db",
Request.DATABASE_UPLOAD_REQUEST(serviceModule), tempDB, serviceModule.getDirectoryPath(), extraParts)) {
FLog.d("Failed to upload database");
return;
}
}
示例5: getTotalLength
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
/**
* Determines the total length of the multipart content (content length of
* individual parts plus that of extra elements required to delimit the parts
* from one another). If any of the @{link BodyPart}s contained in this object
* is of a streaming entity of unknown length the total length is also unknown.
* <p>
* This method buffers only a small amount of data in order to determine the
* total length of the entire entity. The content of individual parts is not
* buffered.
* </p>
*
* @return total length of the multipart entity if known, {@code -1}
* otherwise.
*/
public long getTotalLength() {
long contentLen = 0;
for (final FormBodyPart part: getBodyParts()) {
final ContentBody body = part.getBody();
final long len = body.getContentLength();
if (len >= 0) {
contentLen += len;
} else {
return -1;
}
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
doWriteTo(out, false);
final byte[] extra = out.toByteArray();
return contentLen + extra.length;
} catch (final IOException ex) {
// Should never happen
return -1;
}
}
示例6: generateContentType
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
/**
* @deprecated (4.4) use {@link org.apache.http.entity.mime.FormBodyPartBuilder}.
*/
@Deprecated
protected void generateContentType(final ContentBody body) {
final ContentType contentType;
if (body instanceof AbstractContentBody) {
contentType = ((AbstractContentBody) body).getContentType();
} else {
contentType = null;
}
if (contentType != null) {
addField(MIME.CONTENT_TYPE, contentType.toString());
} else {
final StringBuilder buffer = new StringBuilder();
buffer.append(body.getMimeType()); // MimeType cannot be null
if (body.getCharset() != null) { // charset may legitimately be null
buffer.append("; charset=");
buffer.append(body.getCharset());
}
addField(MIME.CONTENT_TYPE, buffer.toString());
}
}
示例7: testMismatch
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
@Test
public void testMismatch() throws Exception {
ContentBody cb = genContent();
startUpload(cb, 100);
// session - 0
// next expected segment - 1
// epoch - 0
// no such session
tryUploading(cb, journalId, 5, 2, 0, true, false);
// journalId mismatch
tryUploading(cb, journalId + "foo", 0, 1, 0, true, false);
// out of order
tryUploading(cb, journalId, 0, 2, 0, true, false);
// valid segment
tryUploading(cb, journalId, 0, 1, 0, false, false);
// valid + close
tryUploading(cb, journalId, 0, 2, 0, false, true);
// try uploading after close
tryUploading(cb, journalId, 0, 2, 0, true, true);
}
示例8: createImage
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
/**
* Create image with given txid. Finalize and/or delete md5 file if specified.
*/
private void createImage(long txid, boolean finalize, boolean removeMd5)
throws IOException {
// create image
ContentBody cb = genContent(txid);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = TestJournalNodeImageUpload.createRequest(
httpAddress, cb);
UploadImageParam.setHeaders(postRequest, journalId,
FAKE_NSINFO.toColonSeparatedString(), 0, txid, 0, 0, true);
httpClient.execute(postRequest);
if (finalize) {
// roll the image
journal.saveDigestAndRenameCheckpointImage(txid, digests.get(txid));
// remove md5 file if requested which leaves only the image file
if (removeMd5) {
MD5FileUtils.getDigestFileForFile(
journal.getImageStorage().getImageFile(txid)).delete();
}
}
}
示例9: genContent
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
/**
* Generate random contents for the image and store it together with the md5
* for later comparison.
*/
private ContentBody genContent(long txid) throws IOException {
MessageDigest digester = MD5Hash.getDigester();
// write through digester so we can roll the written image
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
DigestOutputStream ds = new DigestOutputStream(bos, digester);
// generate random bytes
new Random().nextBytes(randomBytes);
ds.write(randomBytes);
ds.flush();
// get written hash
MD5Hash hash = new MD5Hash(digester.digest());
// store contents and digest
digests.put(txid, hash);
content.put(txid, Arrays.copyOf(randomBytes, randomBytes.length));
return new ByteArrayBody(bos.toByteArray(), "filename");
}
示例10: testOTAWrongToken
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
@Test
public void testOTAWrongToken() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(400, response.getStatusLine().getStatusCode());
String error = consumeText(response);
assertNotNull(error);
assertEquals("Invalid token.", error);
}
}
示例11: testAuthorizationFailed
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
@Test
public void testAuthorizationFailed() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes()));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(403, response.getStatusLine().getStatusCode());
String error = consumeText(response);
assertNotNull(error);
assertEquals("Authentication failed.", error);
}
}
示例12: basicOTAForNonExistingSingleUser
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
@Test
public void basicOTAForNonExistingSingleUser() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/[email protected]");
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(400, response.getStatusLine().getStatusCode());
String er = consumeText(response);
assertNotNull(er);
assertEquals("Requested user not found.", er);
}
}
示例13: apiUpload
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
/**
* Upload with <a href="http://www.sockshare.com/apidocs.php">API</a>.
*/
private void apiUpload() throws UnsupportedEncodingException, IOException, Exception{
uploading();
ContentBody cbFile = createMonitoredFileBody();
NUHttpPost httppost = new NUHttpPost(apiURL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("file", cbFile);
mpEntity.addPart("user", new StringBody(sockShareAccount.username));
mpEntity.addPart("password", new StringBody(sockShareAccount.password));
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
String reqResponse = EntityUtils.toString(response.getEntity());
//NULogger.getLogger().info(reqResponse);
if(reqResponse.contains("File Uploaded Successfully")){
gettingLink();
downURL = StringUtils.stringBetweenTwoStrings(reqResponse, "<link>", "</link>");
}
else{
//Handle the errors
status = UploadStatus.GETTINGERRORS;
throw new Exception(StringUtils.stringBetweenTwoStrings(reqResponse, "<message>", "</message>"));
}
}
示例14: fileUpload
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
//httppost.setHeader("Cookie", sidcookie+";"+mysessioncookie);
file = new File("h:/UploadingdotcomUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("notprivate", new StringBody("false"));
mpEntity.addPart("folder", new StringBody("/"));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into zippyshare.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
downloadlink=parseResponse(uploadresponse, "value=\"http://", "\"");
downloadlink="http://"+downloadlink;
System.out.println("Download Link : "+downloadlink);
httpclient.getConnectionManager().shutdown();
}
示例15: fileUpload
import org.apache.http.entity.mime.content.ContentBody; //導入依賴的package包/類
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/UploadingdotcomUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("emai", new StringBody("Free"));
mpEntity.addPart("upload_range", new StringBody("1"));
mpEntity.addPart("upfile_0", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into MegaShare.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
uploadresponse = response.getLastHeader("Location").getValue();
System.out.println("Upload response : "+uploadresponse);
System.out.println(response.getStatusLine());
httpclient.getConnectionManager().shutdown();
}