下面列出了org.apache.http.entity.mime.MIME#org.apache.http.entity.mime.content.StringBody 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testFileUpload() throws Exception {
DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
TestHttpClient client = new TestHttpClient();
try {
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
//post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
entity.addPart("file", new FileBody(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
} finally {
client.getConnectionManager().shutdown();
}
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/Sakura haruno.jpg");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("Filedata", cbFile);
// mpEntity.addPart("server", new StringBody(server));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into ugotfile.com");
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
if (response != null) {
uploadresponse = EntityUtils.toString(response.getEntity());
}
System.out.println("Upload Response : " + uploadresponse);
downloadlink = parseResponse(uploadresponse, "[\"", "\"");
downloadlink = downloadlink.replaceAll("\\\\/", "/");
deletelink = parseResponse(uploadresponse, "\",\"", "\"");
deletelink = deletelink.replaceAll("\\\\/", "/");
System.out.println("Download Link : " + downloadlink);
System.out.println("Delete Link : " + deletelink);
}
ContentBody constructContentBody() throws UnsupportedEncodingException {
ContentType contentTypeObject = constructContentTypeObject();
if (filePath != null) { // FILE part
if (contentTypeObject != null) {
return new FileBody(new File(filePath), contentTypeObject);
} else {
return new FileBody(new File(filePath));
}
} else if (content != null) { // TEXT part
if (contentTypeObject != null) {
return new StringBody(content, contentTypeObject);
} else {
return new StringBody(content, ContentType.TEXT_PLAIN);
}
} else { // BYTE ARRAY part
if (contentTypeObject != null) {
return new ByteArrayBody(this.fileBytes, contentTypeObject, fileName);
} else {
return new ByteArrayBody(this.fileBytes, fileName);
}
}
}
private void uploadMixtureCloud() throws Exception {
uploadInitialising();
responseString = NUHttpClientUtils.getData("https://www.mixturecloud.com/files", httpContext);
uploadUrl = "http:" + StringUtils.stringBetweenTwoStrings(responseString, "urlUpload : '", "',");
NULogger.getLogger().log(Level.INFO, "uploadUrl is {0}", uploadUrl);
httpPost = new NUHttpPost(uploadUrl);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("cmd", new StringBody("upload"));
mpEntity.addPart("target", new StringBody("mcm1_MA"));
mpEntity.addPart("upload[]", createMonitoredFileBody());
httpPost.setEntity(mpEntity);
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
HttpEntity resEntity = httpResponse.getEntity();
responseString = EntityUtils.toString(resEntity);
//NULogger.getLogger().log(Level.INFO, "stringResponse : {0}", responseString);
JSONObject jSonObject = new JSONObject(responseString);
String webAccess = jSonObject.getJSONArray("file_data").getJSONObject(0).getString("web_access");
downloadUrl += webAccess;
downURL = downloadUrl;
}
@Test
public void upload() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "upload";
HttpPost post = new HttpPost(getUploadUrl(act));
Map<String, Object> json = new HashMap<>();
json.put("name", "张三");
json.put("age", 23);
String req = Base64.getEncoder().encodeToString(S.json().toJson(json).getBytes(charset));
System.out.println("req:" + req);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("Api", StringBody.create("common", "text/plain", Charset.forName(charset)));
reqEntity.addPart("data", StringBody.create(req, "text/plain", Charset.forName(charset)));
reqEntity.addPart("img", new FileBody(new File("logo_bluce.jpg")));
post.setEntity(reqEntity);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
Assert.assertEquals("HTTP/1.1 200 OK", line);
HttpEntity resEntity = resp.getEntity();
Log.get("upload").info(EntityUtils.toString(resEntity, charset));
}
private static FormBodyPart newFileBody(final String parameterName, final String fileName, final String fileContent)
throws Exception {
return new FormBodyPart(
parameterName,
new StringBody(fileContent, ContentType.TEXT_PLAIN) {
@Override
public String getFilename() {
return fileName;
}
@Override
public String getTransferEncoding() {
return "binary";
}
@Override
public String getMimeType() {
return "";
}
@Override
public String getCharset() {
return null;
}
});
}
public HttpPost initRequest(final FileUploadParameter parameter) {
final FileUploadAddress fileUploadAddress = getDependResult(FileUploadAddress.class);
final HttpPost request = new HttpPost("http://" + fileUploadAddress.getData().getUp() + CONST.URI_PATH);
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Consts.UTF_8);
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart(CONST.QID_NAME, new StringBody(getLoginInfo().getQid(), ContentType.DEFAULT_BINARY));
multipartEntity.addPart("ofmt", new StringBody("json", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("method", new StringBody("Upload.web", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("token", new StringBody(readCookieStoreValue("token"), ContentType.DEFAULT_BINARY));
multipartEntity.addPart("v", new StringBody("1.0.1", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("tk", new StringBody(fileUploadAddress.getData().getTk(), ContentType.DEFAULT_BINARY));
multipartEntity.addPart("Upload", new StringBody("Submit Query", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("devtype", new StringBody("web", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("pid", new StringBody("ajax", ContentType.DEFAULT_BINARY));
multipartEntity.addPart("Filename",
new StringBody(parameter.getUploadFile().getName(), ContentType.APPLICATION_JSON));
multipartEntity.addPart("path", new StringBody(parameter.getPath(), ContentType.APPLICATION_JSON));// 解决中文不识别问题
multipartEntity.addBinaryBody("file", parameter.getUploadFile());
request.setEntity(multipartEntity.build());
return request;
}
public VerificationItems postForm(final Map<String, String> formParamValueMap, final String endpoint, final String boundary){
final HttpPost httpPost = new HttpPost(endpoint);
httpPost.setHeader(MultipartController.VERIFICATION_CONTROL_HEADER_NAME, MultipartController.VERIFICATION_CONTROL_FORM);
try {
for (Map.Entry<String, String> param : formParamValueMap.entrySet()) {
HttpEntity httpEntity = MultipartEntityBuilder
.create()
.setBoundary(boundary)
.setContentType(ContentType.MULTIPART_FORM_DATA)
//.addPart(FormBodyPartBuilder.create().addField(param.getKey(), param.getValue()).build())
.addPart(param.getKey(), new StringBody(param.getValue()))
.build();
httpPost.setEntity(httpEntity);
}
}catch (Exception e){
throw new IllegalStateException("Error preparing the post request", e);
}
return post(httpPost);
}
private static HttpEntity createMessageForComplexForm() {
HttpEntity reqEntity = null;
try {
StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON);
StringBody personList = new StringBody(
"[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]",
ContentType.APPLICATION_JSON);
reqEntity = MultipartEntityBuilder.create().addTextBody("id", "1")
.addPart("company", companyText)
.addPart("people", personList).addBinaryBody("file", new File(
Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()), ContentType.DEFAULT_BINARY, "sample.txt")
.build();
} catch (URISyntaxException e) {
log.error("Error while getting the file from resource." + e.getMessage(), e);
}
return reqEntity;
}
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();
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/install.txt");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into sharesend.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
System.out.println("Upload Response : " + uploadresponse);
System.out.println("Download Link : http://sharesend.com/" + uploadresponse);
httpclient.getConnectionManager().shutdown();
}
@Test
public void testMultiPartRequest() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, StandardCharsets.UTF_8);
entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("PARAMS:\n" +
"name: formValue\n" +
"filename: null\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"formValue\"\n" +
"size: 7\n" +
"content: myValue\n" +
"name: file\n" +
"filename: uploadfile.txt\n" +
"content-type: application/octet-stream\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" +
"Content-Type: application/octet-stream\n" +
"size: 13\n" +
"content: file contents\n", response);
} finally {
client.getConnectionManager().shutdown();
}
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
if (login) {
postURL = "http://upload.badongo.com/mpu_upload.php";
}
HttpPost httppost = new HttpPost(postURL);
file = new File("g:/S2SClient.7z");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
if (login) {
mpEntity.addPart("PHPSESSID", new StringBody(dataid));
}
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into badongo.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());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
// if (resEntity != null) {
// resEntity.consumeContent();
// }
System.out.println("res " + uploadresponse);
httpclient.getConnectionManager().shutdown();
}
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
file = new File("H:\\Dinesh.java");
HttpPost httppost = new HttpPost(oronlink);
if (login) {
httppost.setHeader("Cookie", logincookie + ";" + xfsscookie);
}
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("upload_type", new StringBody("file"));
mpEntity.addPart("srv_id", new StringBody(serverID));
if (login) {
mpEntity.addPart("sess_id", new StringBody(xfsscookie.substring(5)));
}
mpEntity.addPart("srv_tmp_url", new StringBody(tmpserver));
mpEntity.addPart("file_0", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into oron...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
String tmp = EntityUtils.toString(resEntity);
System.out.println("Upload response : " + tmp);
fnvalue = parseResponse(tmp, "name='fn' value='", "'");
System.out.println("fn value : " + fnvalue);
}
// uploadresponse = response.getLastHeader("Location").getValue();
// System.out.println("Upload response : " + uploadresponse);
}
public void fileUpload() throws Exception {
String getsource = NUHttpClientUtils.getData("https://1fichier.com/", httpContext);
doc = Jsoup.parse(getsource);
uploadURL = doc.select("form").first().attr("action");
httpPost = new NUHttpPost(uploadURL);
if (oneFichierAccount.loginsuccessful) {
httpPost.setHeader("Cookie", OneFichierAccount.getSidcookie());
}
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("file[]", createMonitoredFileBody());
mpEntity.addPart("domain", new StringBody("0"));
mpEntity.addPart("submit", new StringBody("Send"));
httpPost.setEntity(mpEntity);
NULogger.getLogger().info("Now uploading your file into 1fichier...........................");
NULogger.getLogger().log(Level.INFO, "Now executing.......{0}", httpPost.getRequestLine());
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
gettingLink();
// HttpEntity resEntity = response.getEntity();
stringResponse = EntityUtils.toString(httpResponse.getEntity());
NULogger.getLogger().info(httpResponse.getStatusLine().toString());
if (httpResponse.containsHeader("Location")) {
uploadresponse = httpResponse.getFirstHeader("Location").getValue();
NULogger.getLogger().log(Level.INFO, "Upload location link : {0}", uploadresponse);
} else {
throw new Exception("There might be a problem with your internet connection or server error. Please try again");
}
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
// if (login) {
// httppost.setHeader("Cookie", cookies.toString());
// }
// httppost.setHeader("Content-Type", "multipart/form-data");
// httppost.setHeader("Host", "upload.crocko.com");
// httppost.setHeader("User-Agent", "Shockwave Flash");
file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\MegaUploadUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
if (login) {
System.out.println("adding php sess .............");
mpEntity.addPart("PHPSESSID", new StringBody(sessionid));
}
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into crocko");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
//
System.out.println("Upload response : " + uploadresponse);
downloadlink = parseResponse(uploadresponse, "Download link:", "</dd>");
downloadlink = parseResponse(downloadlink, "value=\"", "\"");
deletelink = parseResponse(uploadresponse, "Delete link:", "</a></dd>");
deletelink = deletelink.substring(deletelink.indexOf("http://"));
System.out.println("Download link : " + downloadlink);
System.out.println("Delete link : " + deletelink);
}
public MultipartEntity toHttpEntity() {
MultipartEntity entityMultiForm = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
for (Iterator localIterator = keySet().iterator(); localIterator.hasNext();) {
Object element = localIterator.next();
String key = (String) element;
String value = (String) get(key);
entityMultiForm.addPart(key, new StringBody(value, Charset.forName("UTF-8")));
}
} catch (Exception e) {
e.printStackTrace();
}
return entityMultiForm;
}
private void fileUpload() throws Exception {
httpPost = new NUHttpPost(uploadURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("akey", new StringBody(akey));
mpEntity.addPart("Filedata", createMonitoredFileBody());
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into filecloud.io .....");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
HttpEntity resEntity = httpResponse.getEntity();
NULogger.getLogger().info(httpResponse.getStatusLine().toString());
if (resEntity != null) {
stringResponse = EntityUtils.toString(resEntity);
}
stringResponse = httpResponse.getLastHeader("Location").getValue();
stringResponse = StringUtils.stringStartingFromString(stringResponse, "new=");
String downloadURL = "http://filecloud.io/" + stringResponse;
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadURL);
downURL = downloadURL;
status = UploadStatus.UPLOADFINISHED;
}
private static void fileUpload() throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
System.out.println(postURL);
System.out.println(ucookie);
System.out.println(uid);
HttpPost httppost = new HttpPost(postURL);
httppost.setHeader("Cookie", ucookie);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File f = new File("h:/Rock Lee.jpg");
reqEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid));
reqEntity.addPart("u", new StringBody(ucookie));
FileBody bin = new FileBody(f);
reqEntity.addPart("file_0", bin);
reqEntity.addPart("service_1", new StringBody("1"));
reqEntity.addPart("service_16", new StringBody("1"));
reqEntity.addPart("service_7", new StringBody("1"));
reqEntity.addPart("service_17", new StringBody("1"));
reqEntity.addPart("service_9", new StringBody("1"));
reqEntity.addPart("service_10", new StringBody("1"));
reqEntity.addPart("remember_1", new StringBody("1"));
reqEntity.addPart("remember_16", new StringBody("1"));
reqEntity.addPart("remember_7", new StringBody("1"));
reqEntity.addPart("remember_17", new StringBody("1"));
reqEntity.addPart("remember_9", new StringBody("1"));
reqEntity.addPart("remember_10", new StringBody("1"));
httppost.setEntity(reqEntity);
System.out.println("Now uploading your file into multiupload.com. Please wait......................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
System.out.println("Response :\n" + uploadresponse);
uploadresponse = parseResponse(uploadresponse, "\"downloadid\":\"", "\"");
downloadlink = "http://www.multiupload.com/" + uploadresponse;
System.out.println("Download link : " + downloadlink);
}
}
private boolean uploadContent(String filePath, String url, String msg) throws IOException{
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get, context);
this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue();
// load file in form
FileBody cbFile = new FileBody(new File(filePath));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("archive", cbFile);
builder.addPart("subcategory", new StringBody("115", ContentType.MULTIPART_FORM_DATA));
builder.addPart("msg_commit", new StringBody(msg, Charset.forName("UTF-8")));
builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA));
Pair<Integer, String> resultPost = sendPost(url, builder.build());
int statusCode = resultPost.getKey();
switch (statusCode) {
case 200:
return !resultPost.getValue ().contains ("alert-box alert");
case 404:
log.debug("L'id cible du contenu ou le slug est incorrect. Donnez de meilleur informations");
return false;
case 403:
log.debug("Vous n'êtes pas autorisé à uploader ce contenu. Vérifiez que vous êtes connecté");
return false;
case 413:
log.debug("Le fichier que vous essayer d'envoyer est beaucoup trop lourd. Le serveur n'arrive pas à le supporter");
return false;
default:
log.debug("Problème d'upload du contenu. Le code http de retour est le suivant : "+statusCode);
return false;
}
}
private void fileUpload() throws Exception {
HttpClient httpclient = new DefaultHttpClient();
if (badongoAccount.loginsuccessful) {
postURL = "http://upload.badongo.com/mpu_upload.php";
}
HttpPost httppost = new HttpPost(postURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("Filename", new StringBody(file.getName()));
if (badongoAccount.loginsuccessful) {
mpEntity.addPart("PHPSESSID", new StringBody(dataid));
}
mpEntity.addPart("Filedata", createMonitoredFileBody());
httppost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into badongo.com");
uploading();
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// uploadresponse = response.getLastHeader("Location").getValue();
//NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse);
NULogger.getLogger().info(response.getStatusLine().toString());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
// if (resEntity != null) {
// resEntity.consumeContent();
// }
NULogger.getLogger().log(Level.INFO, "res {0}", uploadresponse);
httpclient.getConnectionManager().shutdown();
}
/**
* Posts JSON to a URL
* @param transmissionString
*/
private void publish(String transmissionString)
{
try
{
String iotype = "json";
String fieldName = "json";
String contentType = "application/json";
// String fileName = "filename.graphson";
// upload a GraphSON file
HttpPost httpPost = new HttpPost(apiURL + "/titan");
// byte[] userpass = (userId + ":" + password).getBytes();
// byte[] encoding = Base64.encodeBase64(userpass);
/// httpPost.setHeader("Authorization", "Basic " + new String(encoding));
MultipartEntityBuilder meb = MultipartEntityBuilder.create();
meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
meb.addPart("fieldName", new StringBody(fieldName));
meb.addPart("contentType", new StringBody(contentType));
// meb.addPart("name", new StringBody(fileName));
meb.addTextBody("transaction", transmissionString);
// FileBody fileBody = new FileBody(new File("./data/" + fileName));
// meb.addPart(fieldName, fileBody);
httpPost.setEntity(meb.build());
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// EntityUtils.consume(httpEntity);
String responseString = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(responseString);
} catch (Exception e)
{
e.printStackTrace();
}
}
@Test
public void stringPOSTResponseWithParameter()
throws InterruptedException, ExecutionException, IOException {
File file = new File(getClass().getClassLoader().getResource("payload.xml").getFile());
HttpPost post =
new HttpPost("http://" + HOST + ":" + PORT + SERVICE_REST_GET + "/simpleFilePOSTupload");
HttpClient client = HttpClientBuilder.create().build();
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
StringBody stringBody1 = new StringBody("bar", ContentType.MULTIPART_FORM_DATA);
StringBody stringBody2 = new StringBody("world", ContentType.MULTIPART_FORM_DATA);
//
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody);
builder.addPart("foo", stringBody1);
builder.addPart("hello", stringBody2);
HttpEntity entity = builder.build();
//
post.setEntity(entity);
HttpResponse response = client.execute(post);
// Use createResponse object to verify upload success
final String entity1 = convertStreamToString(response.getEntity().getContent());
System.out.println("-->" + entity1);
assertTrue(entity1.equals("barworlddfgdfg"));
testComplete();
}
@Test
public void testFormDataParamWithSimpleRequest() throws IOException, URISyntaxException {
// Send x-form-url-encoded request
HttpURLConnection connection = request("/test/v1/formDataParam", HttpMethod.POST);
String rawData = "name=wso2&age=10";
ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
try (OutputStream os = connection.getOutputStream()) {
os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
}
InputStream inputStream = connection.getInputStream();
String response = StreamUtil.asString(inputStream);
IOUtils.closeQuietly(inputStream);
connection.disconnect();
assertEquals(response, "wso2:10");
// Send multipart/form-data request
connection = request("/test/v1/formDataParam", HttpMethod.POST);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
HttpEntity build = builder.build();
connection.setRequestProperty("Content-Type", build.getContentType().getValue());
try (OutputStream out = connection.getOutputStream()) {
build.writeTo(out);
}
inputStream = connection.getInputStream();
response = StreamUtil.asString(inputStream);
IOUtils.closeQuietly(inputStream);
connection.disconnect();
assertEquals(response, "wso2:10");
}
public void fileUpload() throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(gruploadlink);
if (gruploadAccount.loginsuccessful) {
httppost.setHeader("Cookie", GRuploadAccount.getLogincookie() + ";" + GRuploadAccount.getXfsscookie());
}
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("upload_type", new StringBody("file"));
// mpEntity.addPart("srv_id", new StringBody(serverID));
if (gruploadAccount.loginsuccessful) {
mpEntity.addPart("sess_id", new StringBody(GRuploadAccount.getXfsscookie().substring(5)));
}
mpEntity.addPart("srv_tmp_url", new StringBody(tmpserver + "/tmp"));
mpEntity.addPart("file_0", createMonitoredFileBody());
httppost.setEntity(mpEntity);
NULogger.getLogger().info("Now uploading your file into grupload...........................");
uploading();
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
NULogger.getLogger().info(response.getStatusLine().toString());
if (resEntity != null) {
String tmp = EntityUtils.toString(resEntity);
NULogger.getLogger().log(Level.INFO, "Upload response : {0}", tmp);
fnvalue = StringUtils.stringBetweenTwoStrings(tmp, "name='fn'>", "<");
NULogger.getLogger().log(Level.INFO, "fn value : {0}", fnvalue);
} else {
throw new Exception("There might be a problem with your internet connection or server error. Please try again some after time. :(");
}
}
private void fileUpload() throws Exception {
//httpClient = new DefaultHttpClient();
httpPost = new NUHttpPost(postURL);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("Filename", new StringBody(getFileName()));
reqEntity.addPart("SID", new StringBody(sid));
reqEntity.addPart("folder_id", new StringBody("0"));
reqEntity.addPart("file", new StringBody(fileID));
reqEntity.addPart("file", createMonitoredFileBody());
reqEntity.addPart("upload", new StringBody("Submit Query"));
httpPost.setEntity(reqEntity);
uploading();
NULogger.getLogger().info("Now uploading your file into uploading.com. Please wait......................");
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
gettingLink();
uploadresponse = EntityUtils.toString(resEntity);
NULogger.getLogger().log(Level.INFO, "PAGE :{0}", uploadresponse);
uploadresponse = StringUtils.stringBetweenTwoStrings(uploadresponse, "answer\":\"", "\"");
downURL = downloadlink;
uploadFinished();
} else {
throw new Exception("There might be a problem with your internet connection or server error. Please try after some time :(");
}
}
private static void getDownloadLink() throws Exception {
// Note : If the response header contains redirection.i.e 302 Found and moved,use the below code to get that moved page
System.out.println("Now Getting Download link...");
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(zsharedomain);
if (login) {
httppost.setHeader("Cookie", xfsscookie);
}
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("fn", new StringBody(fnvalue));
mpEntity.addPart("op", new StringBody("upload_result"));
mpEntity.addPart("st", new StringBody("OK"));
httppost.setEntity(mpEntity);
// h.setHeader("Referer", postURL);
// h.setHeader("Cookie", sidcookie + ";" + mysessioncookie);
HttpResponse res = client.execute(httppost);
HttpEntity entity = res.getEntity();
linkpage = EntityUtils.toString(entity);
System.out.println(linkpage);
downloadlink = parseResponse(linkpage, "Direct Link:</b></td>", "</td>");
downloadlink = parseResponse(downloadlink, "value=\"", "\"");
deletelink = parseResponse(linkpage, "Delete Link:</b></td>", "</td>");
deletelink = parseResponse(deletelink, "value=\"", "\"");
System.out.println("Download link : " + downloadlink);
System.out.println("Delete Link : " + deletelink);
}
@Override
public void run() {
try {
uploadInitialising();
init();
httpGet = new NUHttpGet("http://megaup.me/");
httpResponse = httpclient.execute(httpGet, httpContext);
stringResponse = EntityUtils.toString(httpResponse.getEntity());
document = Jsoup.parse(stringResponse);
Elements elements = document.select("#uploadwindow");
postUrl = elements.select("#uploadform").first().attr("action");
sessionID = elements.select("[name=sessionid]").first().val();
accessKey = elements.select("[name=AccessKey]").first().val();
maxFileSize = elements.select("[name=maxfilesize]").first().val();
phpUploadScript = elements.select("[name=phpuploadscript]").first().val();
returnUrl = elements.select("[name=returnurl]").first().val();
uploadMode = elements.select("[name=uploadmode]").first().val();
NULogger.getLogger().log(Level.INFO, "postUrl: {0}", postUrl);
httpPost = new NUHttpPost(postUrl);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("sessionid", new StringBody(sessionID));
mpEntity.addPart("AccessKey", new StringBody(accessKey));
mpEntity.addPart("maxfilesize", new StringBody(maxFileSize));
mpEntity.addPart("phpuploadscript", new StringBody(phpUploadScript));
mpEntity.addPart("returnurl", new StringBody(returnUrl));
mpEntity.addPart("uploadmode", new StringBody(uploadMode));
mpEntity.addPart("phpuploadscript", new StringBody(phpUploadScript));
mpEntity.addPart("uploadfile_0", createMonitoredFileBody());
mpEntity.addPart("_descr", new StringBody(""));
mpEntity.addPart("_password", new StringBody(""));
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into megaup.me");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
HttpEntity entity = httpResponse.getEntity();
String location = httpResponse.getFirstHeader("Location").getValue();
NULogger.getLogger().log(Level.INFO, "Location: {0}", location);
EntityUtils.consume(entity);
stringResponse = getRequest(location);
stringResponse = getRequest(returnUrl + "?&redir=1");
stringResponse = getRequest("http://megaup.me/getlinks.php?sessionid=" + sessionID + "&submitnums=1");
NULogger.getLogger().log(Level.INFO, "Result:\n{0}", stringResponse);
} catch (Exception ex) {
Logger.getLogger(MegaUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
try {
if (verzendAccount.loginsuccessful) {
userType = "reg";
httpContext = verzendAccount.getHttpContext();
sessionID = CookieUtils.getCookieValue(httpContext, "xfss");
maxFileSizeLimit = 2147483648L; // 2 GB
} else {
userType = "anon";
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
maxFileSizeLimit = 1073741824L; // 1 GB
}
if (file.length() > maxFileSizeLimit) {
throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
}
uploadInitialising();
initialize();
long uploadID;
Random random = new Random();
uploadID = Math.round(random.nextFloat() * Math.pow(10,12));
uploadid_s = String.valueOf(uploadID);
sess_id = StringUtils.stringBetweenTwoStrings(responseString, "name=\"sess_id\" value=\"", "\"");
srv_tmp_url = uploadURL;
uploadURL = StringUtils.removeLastChars(uploadURL, 3) + "cgi-bin/upload.cgi?upload_id=" + uploadid_s + "&js_on=1&utype=" + userType + "&upload_type=file";
httpPost = new NUHttpPost(uploadURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("js_on", new StringBody("1"));
mpEntity.addPart("upload_id", new StringBody(uploadid_s));
mpEntity.addPart("upload_type", new StringBody("file"));
mpEntity.addPart("utype", new StringBody(userType));
mpEntity.addPart("sess_id", new StringBody(sess_id));
mpEntity.addPart("srv_tmp_url", new StringBody(srv_tmp_url));
mpEntity.addPart("file_0_descr", new StringBody(""));
mpEntity.addPart("link_rcpt", new StringBody(""));
mpEntity.addPart("link_pass", new StringBody(""));
mpEntity.addPart("to_folder", new StringBody(""));
mpEntity.addPart("file_0", createMonitoredFileBody());
mpEntity.addPart("submit_btn", new StringBody("Start Upload"));
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into Verzend.be");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
doc = Jsoup.parse(responseString);
//Read the links
gettingLink();
upload_fn = doc.select("textarea[name=fn]").val();
if (upload_fn != null) {
httpPost = new NUHttpPost("http://verzend.be");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("fn", upload_fn));
formparams.add(new BasicNameValuePair("op", "upload_result"));
formparams.add(new BasicNameValuePair("st", "OK"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(entity);
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
doc = Jsoup.parse(responseString);
downloadlink = doc.select("textarea").first().val();
deletelink = doc.select("textarea").eq(1).val();
NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
downURL = downloadlink;
delURL = deletelink;
uploadFinished();
}
} catch(NUException ex){
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}
@Override
public void run() {
try {
if (vShareAccount.loginsuccessful) {
userType = "reg";
httpContext = vShareAccount.getHttpContext();
sessionID = CookieUtils.getCookieValue(httpContext, "xfss");
maxFileSizeLimit = 3196059648L; // 3,048 MB
} else {
userType = "anon";
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
maxFileSizeLimit = 2122317824L; // 2,024 MB
}
addExtensions();
//Check extension
if(!FileUtils.checkFileExtension(allowedVideoExtensions, file)){
throw new NUFileExtensionException(file.getName(), host);
}
if (file.length() > maxFileSizeLimit) {
throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
}
uploadInitialising();
initialize();
long uploadID;
Random random = new Random();
uploadID = Math.round(random.nextFloat() * Math.pow(10,12));
uploadid_s = String.valueOf(uploadID);
sess_id = StringUtils.stringBetweenTwoStrings(responseString, "name=\"sess_id\" value=\"", "\"");
srv_tmp_url = uploadURL;
uploadURL = StringUtils.removeLastChars(uploadURL, 3) + "cgi-bin/upload.cgi?upload_id=" + uploadid_s + "&js_on=1&utype=" + userType + "&upload_type=file";
httpPost = new NUHttpPost(uploadURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("js_on", new StringBody("1"));
mpEntity.addPart("upload_id", new StringBody(uploadid_s));
mpEntity.addPart("upload_type", new StringBody("file"));
mpEntity.addPart("utype", new StringBody(userType));
mpEntity.addPart("sess_id", new StringBody(sess_id));
mpEntity.addPart("srv_tmp_url", new StringBody(srv_tmp_url));
mpEntity.addPart("file_0_descr", new StringBody(""));
mpEntity.addPart("file_0_public", new StringBody("1"));
mpEntity.addPart("file_0", createMonitoredFileBody());
mpEntity.addPart("submit_btn", new StringBody("Done"));
mpEntity.addPart("tos", new StringBody("1"));
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into VShare.eu");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
doc = Jsoup.parse(responseString);
//Read the links
gettingLink();
upload_fn = doc.select("textarea[name=fn]").val();
if (upload_fn != null) {
httpPost = new NUHttpPost("http://vshare.eu/");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("fn", upload_fn));
formparams.add(new BasicNameValuePair("op", "upload_result"));
formparams.add(new BasicNameValuePair("st", "OK"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(entity);
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
doc = Jsoup.parse(responseString);
downloadlink = doc.select("textarea").first().val();
deletelink = doc.select("textarea").eq(2).val();
NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
downURL = downloadlink;
delURL = deletelink;
uploadFinished();
}
} catch(NUException ex){
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}