本文整理匯總了Java中com.sun.jersey.multipart.FormDataMultiPart.bodyPart方法的典型用法代碼示例。如果您正苦於以下問題:Java FormDataMultiPart.bodyPart方法的具體用法?Java FormDataMultiPart.bodyPart怎麽用?Java FormDataMultiPart.bodyPart使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.sun.jersey.multipart.FormDataMultiPart
的用法示例。
在下文中一共展示了FormDataMultiPart.bodyPart方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: serialize
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
示例2: upload
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
public void upload(String fileName, String sourceId,
String fileTypeId, InputStream inputStream)
throws ClientException {
String path = UriBuilder
.fromPath("/api/protected/file/upload/")
.segment(sourceId)
.segment(fileTypeId)
.build().toString();
FormDataMultiPart part = new FormDataMultiPart();
part.bodyPart(
new FormDataBodyPart(
FormDataContentDisposition
.name("file")
.fileName(fileName)
.build(),
inputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE));
doPostMultipart(path, part);
}
示例3: doUploadFile
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
ClientResponse.Status doUploadFile(WebResource webResource, File file, String sourceId, String fileTypeId) throws ClientHandlerException, UniformInterfaceException, IOException {
try (InputStream is = new FileInputStream(file)) {
FormDataMultiPart part =
new FormDataMultiPart();
part.bodyPart(
new FormDataBodyPart(
FormDataContentDisposition
.name("file")
.fileName(file.getName())
.build(),
is, MediaType.APPLICATION_OCTET_STREAM_TYPE));
ClientResponse response = webResource
.path("/api/protected/file/upload/" + sourceId + "/" + fileTypeId)
.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, part);
ClientResponse.Status result = response.getClientResponseStatus();
return result;
}
}
示例4: serialize
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param : formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
示例5: upload
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
public ClientResponse<File> upload(String url, File f, Headers... headers) {
@SuppressWarnings("resource")
FormDataMultiPart form = new FormDataMultiPart();
form.bodyPart(new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE));
String urlCreated = createURI(url);
ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(MultiPartWriter.class);
WebResource webResource = Client.create(cc).resource(urlCreated);
Builder builder = webResource.type(MULTIPART_MEDIA).accept(MEDIA).accept("text/plain");
for (Headers h : headers) {
builder.header(h.getKey(), h.getValue());
}
com.sun.jersey.api.client.ClientResponse clienteResponse = null;
clienteResponse = builder.post(com.sun.jersey.api.client.ClientResponse.class, form);
return new ClientResponse<File>(clienteResponse, File.class);
}
示例6: upload
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
/**
* upload from the given inputstream
*
* @param fileToUpload
* @param filename
* @param contents
* @param comment
* @throws Exception
*/
public synchronized void upload(InputStream fileToUpload, String filename,
String contents, String comment) throws Exception {
TokenResult token = getEditToken("File:" + filename, "edit");
final FormDataMultiPart multiPart = new FormDataMultiPart();
// http://stackoverflow.com/questions/5772225/trying-to-upload-a-file-to-a-jax-rs-jersey-server
multiPart.bodyPart(new StreamDataBodyPart("file", fileToUpload));
multiPart.field("filename", filename);
multiPart.field("ignorewarnings", "true");
multiPart.field("text", contents);
if (!comment.isEmpty())
multiPart.field("comment", comment);
String params = "";
Api api = this.getActionResult("upload", params, token, multiPart);
handleError(api);
}
示例7: sendComplexMessage
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
private ClientResponse sendComplexMessage(String recipient) {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
WebResource webResource = client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME
+ "/messages");
FormDataMultiPart formData = new FormDataMultiPart();
formData.field("from", "Mailgun User <[email protected]" + MAILGUN_DOMAIN_NAME + ">");
formData.field("to", recipient);
formData.field("subject", "Complex Mailgun Example");
formData.field("html", "<html>HTML <strong>content</strong></html>");
ClassLoader classLoader = getClass().getClassLoader();
File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, formData);
}
示例8: sendComplexMessage
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
private ClientResponse sendComplexMessage(String recipient) {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
FormDataMultiPart formData = new FormDataMultiPart();
formData.field("from", "Mailgun User <[email protected]" + MAILGUN_DOMAIN_NAME + ">");
formData.field("to", recipient);
formData.field("subject", "Complex Mailgun Example");
formData.field("html", "<html>HTML <strong>content</strong></html>");
ClassLoader classLoader = getClass().getClassLoader();
File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
WebResource webResource = client.resource(
"https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, formData);
}
示例9: sendComplexMessage
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
@SuppressWarnings("VariableDeclarationUsageDistance")
private ClientResponse sendComplexMessage(String recipient) {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
WebResource webResource =
client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
FormDataMultiPart formData = new FormDataMultiPart();
formData.field("from", "Mailgun User <[email protected]" + MAILGUN_DOMAIN_NAME + ">");
formData.field("to", recipient);
formData.field("subject", "Complex Mailgun Example");
formData.field("html", "<html>HTML <strong>content</strong></html>");
ClassLoader classLoader = getClass().getClassLoader();
File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
return webResource
.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, formData);
}
示例10: uploadTestImage
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
static private String uploadTestImage() {
TwitterAdsClient.setTrace(false);
TwitterAdsClient.setSandbox(true);
// upload image
String domain = "https://upload.twitter.com";
String resource = "/1.1/media/upload.json";
String filePath = "src/test/resources/angry.bird.800.320.png";
ClientService clientService = ClientServiceFactory.getInstance();
Client client = clientService.getClient();
WebResource webResource = client.resource(domain);
final FileDataBodyPart filePart = new FileDataBodyPart("media", new File(filePath));
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
FormDataMultiPart multiPart = (FormDataMultiPart) formDataMultiPart.bodyPart(filePart);
ClientResponse response = webResource.path(resource).type(MediaType.MULTIPART_FORM_DATA_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
JsonObject jsonObj = new JsonParser().parse(output).getAsJsonObject();
return jsonObj.get("media_id_string").getAsString();
}
示例11: persistAttachments
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
private void persistAttachments(ODocument item, Issue issue) throws IOException {
AttachmentStorage storage = new AttachmentStorage();
String id = item.field(FieldNames.ID);
List<Attachment> attachments = storage.readAttachments(Long.parseLong(id));
if (attachments.size() > 0) {
List<String> alreadyExportedAttachments = getAlreadyExportedAttachments(issue);
final FormDataMultiPart multiPart = new FormDataMultiPart();
int newlyAdded = 0;
for (Attachment attachment : attachments) {
// check if already exported
if (!alreadyExportedAttachments.contains(attachment.getPath().getFileName().toString())) {
final File fileToUpload = attachment.getPath().toFile();
if (fileToUpload != null) {
multiPart.bodyPart(new FileDataBodyPart("file", fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));
newlyAdded++;
}
}
}
if (newlyAdded > 0) {
try {
getRestAccess().postMultiPart(issue.getSelfPath() + "/attachments", multiPart);
} catch (Exception e) {
LOGGER.severe("Could not upload attachments");
}
}
}
}
示例12: main
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
public static void main(String args[]) throws Exception {
Properties properties = new Properties();
InputStream input = null;
try {
input = new FileInputStream("src/main/resources/config.properties");
properties.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
ClientServiceFactory.consumerKey = properties.getProperty("consumer.key");
ClientServiceFactory.consumerSecret = properties.getProperty("consumer.secret");
ClientServiceFactory.accessToken = properties.getProperty("access.token");
ClientServiceFactory.accessTokenSecret = properties.getProperty("access.secret");
String domain = "https://upload.twitter.com";
String resource = "/1.1/media/upload.json";
// String filePath = "C:/temp/twitter.jpeg";
String filePath = "src/test/resources/angry.bird.800.320.png";
ClientService clientService = ClientServiceFactory.getInstance();
Client client = clientService.getClient();
WebResource webResource = client.resource(domain);
webResource.addFilter(new LoggingFilter());
final FileDataBodyPart filePart = new FileDataBodyPart("media", new File(filePath));
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
FormDataMultiPart multiPart = (FormDataMultiPart) formDataMultiPart.bodyPart(filePart);
ClientResponse response = webResource.path(resource).type(MediaType.MULTIPART_FORM_DATA_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println(output);
JsonObject jsonObj = new JsonParser().parse(output).getAsJsonObject();
String mediaId = jsonObj.get("media_id_string").getAsString();
System.out.println("media id = "+ mediaId);
}
示例13: testLeadGenCard
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
@Test
public void testLeadGenCard() throws Exception {
TwitterAdsClient.setTrace(true);
TwitterAdsClient.setSandbox(false);
Account account = client.getAccount(ACCOUNT_ID);
String domain = "https://upload.twitter.com";
String resource = "/1.1/media/upload.json";
String filePath = "src/test/resources/test.image.800.200.png";
ClientService clientService = ClientServiceFactory.getInstance();
Client uploadClient = clientService.getClient();
WebResource webResource = uploadClient.resource(domain);
final FileDataBodyPart filePart = new FileDataBodyPart("media", new File(filePath));
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
FormDataMultiPart multiPart = (FormDataMultiPart) formDataMultiPart.bodyPart(filePart);
ClientResponse response = webResource.path(resource).type(MediaType.MULTIPART_FORM_DATA_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
JsonObject jsonObj = new JsonParser().parse(output).getAsJsonObject();
String mediaIdString = jsonObj.get("media_id_string").getAsString();
LeadGenCard leadGenCard = LeadGenCard.builder().account(account).name("british_celebratory_card")
.title("Some leadgen card title").image_media_id(mediaIdString).fallback_url("https://dev.twitter.com")
.privacy_policy_url("https://twitter.com/privacy").cta("test").build();
assertNotNull(LeadGenCard.builder().toString());
leadGenCard.save();
assertTrue("Leadgencard has an id generated", leadGenCard.toString().contains("id"));
leadGenCard.setName("updated_british_celebratory_card");
leadGenCard.setTitle("Some leadgen card title Updated");
leadGenCard.setImage_media_id(mediaIdString);
leadGenCard.setFallback_url("https://dev.twitter.com/api");
leadGenCard.setPrivacy_policy_url("https://twitter.com/privacy");
leadGenCard.setCta("UpdatedJoin our List");
leadGenCard.save();
assertTrue("lead gen card name has been updated",
leadGenCard.getName().equals("updated_british_celebratory_card"));
String id = leadGenCard.getId();
leadGenCard = new LeadGenCard(account);
leadGenCard.setId(id);
leadGenCard.load();
assertTrue("lead gen card name has been loaded",
leadGenCard.getName().equals("updated_british_celebratory_card"));
// clean up
leadGenCard.delete();
assertTrue("Lead gen card card has been deleted", leadGenCard.isDeleted());
}
示例14: nlpSegmentationSegmentAndTokenizeGet
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
/**
* Segment and tokenize\n
* Segment an input text, then tokenize each segment.\n
* @param inputFile input text\n\n**Either `input` or `inputFile` is required**\n
* @param input input text\n\n**Either `input` or `inputFile` is required**\n
* @param lang Language code of the input ([details](#description_langage_code_values))
* @param profile Profile id\n
* @param callback Javascript callback function name for JSONP Support\n
* @return SegmentationSegmentAndTokenizeResponse
*/
public SegmentationSegmentAndTokenizeResponse nlpSegmentationSegmentAndTokenizeGet (File inputFile, String input, String lang, Integer profile, String callback) throws ApiException {
Object postBody = null;
// verify the required parameter 'lang' is set
if (lang == null) {
throw new ApiException(400, "Missing the required parameter 'lang' when calling nlpSegmentationSegmentAndTokenizeGet");
}
// create path and map variables
String path = "/nlp/segmentation/segmentAndTokenize".replaceAll("\\{format\\}","json");
// query params
Map<String, Object> queryParams = new HashMap<String, Object>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
if (input != null)
queryParams.put("input", apiClient.parameterToString(input));
if (lang != null)
queryParams.put("lang", apiClient.parameterToString(lang));
if (profile != null)
queryParams.put("profile", apiClient.parameterToString(profile));
if (callback != null)
queryParams.put("callback", apiClient.parameterToString(callback));
final String[] accepts = {
"application/json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"multipart/form-data", "application/x-www-form-urlencoded", "*/*"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if (inputFile != null) {
hasFields = true;
mp.field("inputFile", inputFile.getName());
mp.bodyPart(new FileDataBodyPart("inputFile", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE));
}
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { "accessToken", "apiKey" };
ClientResponse response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (SegmentationSegmentAndTokenizeResponse) apiClient.deserialize(response, "", SegmentationSegmentAndTokenizeResponse.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
示例15: nlpSegmentationTokenizeGet
import com.sun.jersey.multipart.FormDataMultiPart; //導入方法依賴的package包/類
/**
* Tokenize\n
* Tokenize an input text.\n
* @param inputFile input text\n\n**Either `input` or `inputFile` is required**\n
* @param input input text\n\n**Either `input` or `inputFile` is required**\n
* @param lang Language code of the input ([details](#description_langage_code_values))
* @param profile Profile id\n
* @param callback Javascript callback function name for JSONP Support\n
* @return SegmentationTokenizeResponse
*/
public SegmentationTokenizeResponse nlpSegmentationTokenizeGet (File inputFile, String input, String lang, Integer profile, String callback) throws ApiException {
Object postBody = null;
// verify the required parameter 'lang' is set
if (lang == null) {
throw new ApiException(400, "Missing the required parameter 'lang' when calling nlpSegmentationTokenizeGet");
}
// create path and map variables
String path = "/nlp/segmentation/tokenize".replaceAll("\\{format\\}","json");
// query params
Map<String, Object> queryParams = new HashMap<String, Object>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
if (input != null)
queryParams.put("input", apiClient.parameterToString(input));
if (lang != null)
queryParams.put("lang", apiClient.parameterToString(lang));
if (profile != null)
queryParams.put("profile", apiClient.parameterToString(profile));
if (callback != null)
queryParams.put("callback", apiClient.parameterToString(callback));
final String[] accepts = {
"application/json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"multipart/form-data", "application/x-www-form-urlencoded", "*/*"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if (inputFile != null) {
hasFields = true;
mp.field("inputFile", inputFile.getName());
mp.bodyPart(new FileDataBodyPart("inputFile", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE));
}
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { "accessToken", "apiKey" };
ClientResponse response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (SegmentationTokenizeResponse) apiClient.deserialize(response, "", SegmentationTokenizeResponse.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}