Java Examples for org.apache.http.entity.mime.content.StringBody
The following java examples will help you to understand the usage of org.apache.http.entity.mime.content.StringBody. These source code samples are taken from different open source projects.
Example 1
Project: mobile-ecommerce-android-education-master File: MultipartPost.java View source code |
public void executeMultipartPost() throws Exception { try { InputStream is = this.getAssets().open("data.xml"); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://192.178.10.131/WS2/Upload.aspx"); byte[] data = IOUtils.toByteArray(is); InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), "uploadedFile"); StringBody sb1 = new StringBody("someTextGoesHere"); StringBody sb2 = new StringBody("someTextGoesHere too"); MultipartEntity multipartContent = new MultipartEntity(); multipartContent.addPart("uploadedFile", isb); multipartContent.addPart("one", sb1); multipartContent.addPart("two", sb2); postRequest.setEntity(multipartContent); HttpResponse res = httpClient.execute(postRequest); res.getEntity().getContent().close(); } catch (Throwable e) { } }
Example 2
Project: neembuu-uploader-master File: Hostr.java View source code |
@Override
public void run() {
try {
if (hostrAccount.loginsuccessful) {
host = hostrAccount.username + " | Hostr.co";
} else {
host = "Hostr.co";
uploadInvalid();
return;
}
if (file.length() > hostrAccount.getMaxFileSize()) {
throw new NUMaxFileSizeException(hostrAccount.getMaxFileSize(), file.getName(), hostrAccount.getHOSTNAME());
}
uploadInitialising();
UsernamePasswordCredentials upc = new UsernamePasswordCredentials(hostrAccount.getUsername(), hostrAccount.getPassword());
httpPost = new NUHttpPost("http://api.hostr.co/file");
httpPost.addHeader(new BasicScheme().authenticate(upc, httpPost));
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("name", new StringBody(file.getName()));
mpEntity.addPart("file", createMonitoredFileBody());
httpPost.setEntity(mpEntity);
NULogger.getLogger().info("Now uploading your file into hostr...........................");
uploading();
httpResponse = httpclient.execute(httpPost);
gettingLink();
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
String tmp = EntityUtils.toString(resEntity);
JSONObject json = new JSONObject(tmp);
//Handle the errors
if (json.has("error")) {
//@todo: we must stop all upload in localhostr.com if you have exceeded the upload limit
HostrApiBuilder hostrApiBuilder = new HostrApiBuilder();
HostrApi hostrApi = hostrApiBuilder.setDailyUploadAllowance(hostrAccount.getDailyUploadAllowance()).setFileName(file.getName()).setFileSizeLimit(hostrAccount.getMaxFileSize()).setHostname(hostrAccount.getHOSTNAME()).setJSONObject(json).setUsername(hostrAccount.getUsername()).build();
hostrApi.handleErrors();
}
downURL = json.getString("href");
NULogger.getLogger().log(Level.INFO, "Download link: {0}", downURL);
status = UploadStatus.UPLOADFINISHED;
uploadFinished();
} else {
throw new Exception();
}
} catch (NUException ex) {
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}
Example 3
Project: pdfcombinercco-master File: FileUploader.java View source code |
/** * Method that builds the multi-part form data request * @param urlString the urlString to which the file needs to be uploaded * @param file the actual file instance that needs to be uploaded * @param jsonBody * @return server response as <code>String</code> */ public String executeMultiPartRequest(String urlString, File file, String jsonBody, Map<String, String> headerMap) { HttpPost postRequest = new HttpPost(urlString); if (headerMap != null) { for (String headerKey : headerMap.keySet()) { postRequest.addHeader(headerKey, headerMap.get(headerKey)); } } MultipartEntity multiPartEntity = new MultipartEntity(); // add json body StringBody jsonContentStringBody = org.apache.http.entity.mime.content.StringBody.create(jsonBody, "application/json", Charset.forName("UTF-8")); multiPartEntity.addPart("entity_content", jsonContentStringBody); /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part. This part will be considered as file part and the rest of them as usual form-data parts*/ FileBody fileBody = new FileBody(file, "application/octect-stream"); multiPartEntity.addPart("VersionData", fileBody); postRequest.setEntity(multiPartEntity); return executeRequest(postRequest); }
Example 4
Project: aq2o-master File: JettyMultipartTest.java View source code |
public void testApp() throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:44444/csv/"); MultipartEntity reqEntity = new MultipartEntity(); StringBody seriesId = new StringBody("S1"); StringBody field = new StringBody("F1"); StringBody freq = new StringBody("RAW"); reqEntity.addPart("SERIESID", seriesId); reqEntity.addPart("FIELD", field); reqEntity.addPart("FREQ", freq); reqEntity.addPart("DATA", new StringBody("1,1\n2,2\n3,3\n")); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); assertTrue(true); }
Example 5
Project: carrot2-master File: HttpClientPostProvider.java View source code |
public InputStream post(URI dcsURI, Map<String, String> attributes) throws IOException {
final HttpClient client = new DefaultHttpClient();
final HttpPost post = new HttpPost(dcsURI);
final MultipartEntity body = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF8);
for (Map.Entry<String, String> entry : attributes.entrySet()) {
body.addPart(entry.getKey(), new StringBody(entry.getValue(), UTF8));
}
post.setEntity(body);
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Unexpected DCS response: " + response.getStatusLine());
}
final byte[] responseBody = StreamUtils.readFullyAndClose(response.getEntity().getContent());
return new ByteArrayInputStream(responseBody);
} finally {
client.getConnectionManager().shutdown();
}
}
Example 6
Project: deliciousfruit-master File: ErpMessageSender.java View source code |
public String sendPostMsg(String message, String url) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart(JSONCODE, new StringBody(message, Charset.forName(UTF_8)));
httppost.setEntity(entity);
HttpResponse response = null;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
String responseContent = "";
if (resEntity != null) {
responseContent = EntityUtils.toString(resEntity, UTF_8);
EntityUtils.consume(resEntity);
}
httpclient.getConnectionManager().shutdown();
return Encoder.decodeUnicode(responseContent);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
} catch (ClientProtocolException e) {
log.error(e.getMessage(), e);
} catch (ParseException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}
Example 7
Project: meteor-master File: HttpUploadClient.java View source code |
private MultipartEntity setPartEntity(BaseAPI param) throws UnsupportedEncodingException {
MultipartEntity multipartContent = new MultipartEntity();
//处ç?†é?žæ–‡ä»¶ç±»æ??交
for (int i = 0; i < param.getValuePair().size(); i++) {
if (param.getValuePair().get(i) != null) {
multipartContent.addPart(param.getValuePair().get(i).getName(), new StringBody(param.getValuePair().get(i).getValue(), Charset.forName(HTTP.UTF_8)));
}
}
//处ç?†æ–‡ä»¶ç±»æ??交
for (int i = 0; i < param.getFileList().size(); i++) {
if (param.getFileList().get(i) != null) {
multipartContent.addPart(param.getFileList().get(i).getName(), new FileBody(new File(param.getFileList().get(i).getValue())));
}
}
return multipartContent;
}
Example 8
Project: sling-master File: ValidationServiceIT.java View source code |
@Test public void testValidRequestModel1() throws IOException, JSONException { final String url = String.format("http://localhost:%s", httpPort()); final RequestBuilder requestBuilder = new RequestBuilder(url); MultipartEntity entity = new MultipartEntity(); entity.addPart("sling:resourceType", new StringBody("validation/test/resourceType1")); entity.addPart("field1", new StringBody("HELLOWORLD")); entity.addPart("field2", new StringBody("30.01.1988")); entity.addPart(SlingPostConstants.RP_OPERATION, new StringBody("validation")); RequestExecutor re = requestExecutor.execute(requestBuilder.buildPostRequest("/validation/testing/fakeFolder1/resource").withEntity(entity)).assertStatus(200); String content = re.getContent(); JSONObject jsonResponse = new JSONObject(content); assertTrue(jsonResponse.getBoolean("valid")); }
Example 9
Project: socom-master File: FBPostRequest.java View source code |
private ContentBody packValue(Object valueObject) {
ContentBody body = null;
if (valueObject instanceof String) {
body = new StringBody((String) valueObject, ContentType.DEFAULT_TEXT);
} else if (valueObject instanceof File) {
body = new FileBody((File) valueObject);
} else if (valueObject instanceof InputStream) {
body = new InputStreamBody((InputStream) valueObject, "photos");
} else if (valueObject instanceof byte[]) {
//XXX is null here ok?
body = new ByteArrayBody((byte[]) valueObject, null);
}
return body;
}
Example 10
Project: commcare-odk-master File: ExceptionReportTask.java View source code |
/* * (non-Javadoc) * @see android.os.AsyncTask#doInBackground(java.lang.Object[]) */ @Override protected String doInBackground(Throwable... values) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); //TODO: This is ridiculous. Just do the normal log submission process DeviceReportWriter report; try { report = new DeviceReportWriter(baos); } catch (IOException e) { report = null; } String fallbacktext = null; for (Throwable ex : values) { String exceptionText = getStackTrace(ex); if (fallbacktext == null) { fallbacktext = exceptionText; } if (report != null) { report.addReportElement(new AndroidLogSerializer(new AndroidLogEntry("forceclose", exceptionText, new Date()))); } } byte[] data; try { if (report == null) { throw new IOException(); } report.write(); data = baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); String fsDate = new Date().toString(); data = ("<?xml version='1.0' ?><n0:device_report xmlns:n0=\"http://code.javarosa.org/devicereport\"><device_id>FAILSAFE</device_id><report_date>" + fsDate + "</report_date><log_subreport><log_entry date=\"" + fsDate + "\"><entry_type>forceclose</entry_type><entry_message>" + fallbacktext + "</entry_message></log_entry></log_subreport></device_report>").getBytes(); } String URI = CommCareApplication._().getString(R.string.PostURL); try { SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); URI = settings.getString("PostURL", CommCareApplication._().getString(R.string.PostURL)); } catch (Exception e) { } //TODO: Send this with the standard logging subsystem String payload = new String(data); System.out.println("Outgoing payload: " + payload); MultipartEntity entity = new MultipartEntity(); try { //Apparently if you don't have a filename in the multipart wrapper, some receivers //don't properly receive this post. StringBody body = new StringBody(payload, "text/xml", MIME.DEFAULT_CHARSET) { /* * (non-Javadoc) * @see org.apache.http.entity.mime.content.StringBody#getFilename() */ @Override public String getFilename() { return "exceptionreport.xml"; } }; entity.addPart("xml_submission_file", body); } catch (IllegalCharsetNameException e1) { e1.printStackTrace(); } catch (UnsupportedCharsetException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } HttpRequestGenerator generator; try { User user = CommCareApplication._().getSession().getLoggedInUser(); if (user.getUserType().equals(User.TYPE_DEMO)) { generator = new HttpRequestGenerator(); } else { generator = new HttpRequestGenerator(user); } } catch (Exception e) { generator = new HttpRequestGenerator(); } try { HttpResponse response = generator.postData(URI, entity); ByteArrayOutputStream bos = new ByteArrayOutputStream(); response.getEntity().writeTo(bos); System.out.println("Response: " + new String(bos.toByteArray())); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //We seem to have to return something... return null; }
Example 11
Project: dtgov-master File: Multipart.java View source code |
public void post(HttpClient httpclient, URI uri, Map<String, Object> parameters) throws IOException, WorkflowException { MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (String key : parameters.keySet()) { ContentBody content = null; Object param = parameters.get(key); if (param instanceof String) { //$NON-NLS-1$ //$NON-NLS-2$ StringBody stringBody = new StringBody((String) param, "text/plain", Charset.forName("UTF-8")); content = stringBody; } else { //turn object into byteArray, or it also supports InputStreamBody or FileBody ByteArrayBody byteBody = new ByteArrayBody(null, key); content = byteBody; } multiPartEntity.addPart(key, content); } HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(multiPartEntity); HttpResponse response = httpclient.execute(httpPost); InputStream is = response.getEntity().getContent(); String responseStr = IOUtils.toString(is); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) { logger.debug(responseStr); } else { throw new WorkflowException(//$NON-NLS-1$ //$NON-NLS-2$ "Workflow ERROR - HTTP STATUS CODE " + response.getStatusLine().getStatusCode() + ". " + response.getStatusLine().getReasonPhrase() + ". " + //$NON-NLS-1$ responseStr); } is.close(); }
Example 12
Project: geppetto-master File: OAuthModule.java View source code |
@Override public AuthResponse authenticate(HttpClient httpClient) throws IOException { HttpPost request = new HttpPost(oauthURL); MultipartEntity entity = new MultipartEntity(); entity.addPart("grant_type", new StringBody("password")); entity.addPart("client_id", new StringBody(clientId)); entity.addPart("client_secret", new StringBody(clientSecret)); entity.addPart("username", new StringBody(username)); entity.addPart("password", new StringBody(password)); request.setEntity(entity); return httpClient.execute(request, new JSonResponseHandler<OAuthResponse>(gson, OAuthResponse.class)); }
Example 13
Project: android-raovattructuyen-master File: JsonHandler.java View source code |
public static JSONObject getJsonFromUpload(String url, String path, ArrayList<PairValue> value) { InputStream is = null; String json = null; JSONObject jObject = null; System.out.println("url" + url); // tao http request try { File f = null; // defaultHttpCLient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); //FileEntity MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (!path.equals("")) f = new File(path); else { f = new File(""); } FileBody fileBody = new FileBody(f); entity.addPart("file", fileBody); httpPost.setEntity(entity); System.out.println("ttttt"); if (value != null && value.size() != 0) { for (int i = 0; i < value.size(); i++) { System.out.println("xxx " + value.get(i).getName() + value.get(i).getValue()); PairValue p = value.get(i); FormBodyPart part = new FormBodyPart(p.getName(), new StringBody(p.getValue())); entity.addPart(part); } } // FormBodyPart part = new FormBodyPart("ppp", new StringBody("111")); // entity.addPart(part); //System.out.println(EntityUtils.toString(httpPost.getEntity())+"checkloi"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); sb.append(line + "n"); } is.close(); reader.close(); json = sb.toString(); } catch (Exception e) { Log.e("error tai day", e.toString()); } // parse object to json try { jObject = new JSONObject(json); } catch (JSONException e) { Log.e("JSon error", e.toString()); } return jObject; }
Example 14
Project: Assassins-Test-master File: KillActivity.java View source code |
public void onPictureTaken(byte[] imageData, Camera c) {
Log.v("camera info:", "got there:" + (imageData == null));
if (imageData != null) {
Intent mIntent = new Intent();
AssassinsApplication app = new AssassinsApplication();
// Bitmap bitmap=
// BitmapFactory.decodeByteArray(imageData,0,imageData.length);
// String imageString=Base64.encodeToString(imageData
// ,Base64.DEFAULT);
String url = InGameService.BASE_URL + "ingame/killrequest/";
HttpPost httppost = new HttpPost(url);
// Log.v("camera info:","string respresentation:"
// +imageString.toString() );
// List<NameValuePair> nameValuePairs = new
// ArrayList<NameValuePair>();
// nameValuePairs.add(new
// BasicNameValuePair("access_token",facebook.getAccessToken()));
// nameValuePairs.add(new
// BasicNameValuePair("picture",imageString));
// Log.v("taking pic, ",httppost.toString());
// Log.v("camera info:","value pairs 0 :"
// +nameValuePairs.get(0).toString());
// Log.v("camera info:","value pairs 1 :"
// +nameValuePairs.get(1).toString());
// Log.v("camera info:","value pairs :"
// +nameValuePairs.toString());
MultipartEntity mp = new MultipartEntity();
ContentBody cb = new ByteArrayBody(imageData, "image/jpeg", "picture.jpg");
mp.addPart("picture", cb);
try {
ContentBody token = new StringBody(app.getAccessToken());
mp.addPart("access_token", token);
httppost.setEntity(mp);
InGameService.request(url, false, httppost);
} catch (Exception /** UnsupportedEncodingException **/
e) {
e.printStackTrace();
}
mCamera.startPreview();
setResult(FOTO_MODE, mIntent);
}
}
Example 15
Project: BigFileUploadJava-master File: ApacheHCUploader.java View source code |
@Override public void done(String fileName, long partCount) { Map<String, ContentBody> params = new HashMap<String, ContentBody>(); try { params.put(Config.keyFileName, new StringBody(fileName)); params.put(Config.keyPartCount, new StringBody(String.valueOf(partCount))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } post(params); log.debug(fileName + " notification is done."); }
Example 16
Project: ccshop-master File: CallRechargeHelper.java View source code |
private static boolean doGetSource(String MerID, String MerAccount, String OrderID, String CardType, int Value, int timeout, String Province, String ReplyFormat, int Command, String InterfaceName, String InterfaceNumber, String CardSn, String CardKey, String ChargeNo, String Datetime, String TranOrder, String MerURL, String KEY) throws Exception { String OrderInfo = MerID + "|" + MerAccount + "|" + OrderID + "|" + CardType + "|" + Value + "|" + timeout + "|" + Province + "|" + ReplyFormat + "|" + Command + "|" + InterfaceName + "|" + InterfaceNumber + "|" + CardSn + "|" + CardKey + "|" + ChargeNo + "|" + Datetime + "|" + TranOrder + "|" + MerURL + "|"; String Sign = Sec.MD5Encrypt(OrderInfo + "|" + KEY, 32); System.out.println("OrderInfo=" + OrderInfo); // System.out.println("Sign="+Sign); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Config.CALL_URL_RECVCDKEY); // 多部分的实体 MultipartEntity reqEntity = new MultipartEntity(); // å¢žåŠ reqEntity.addPart("Orderinfo", new StringBody(OrderInfo)); reqEntity.addPart("Sign", new StringBody(Sign)); // 设置 httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); InputStream inStream = resEntity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = -1; while ((len = inStream.read(data)) != -1) { baos.write(data, 0, len); } byte[] result = baos.toByteArray(); String message = new String(result, "GB2312"); if (!StringUtils.isEmpty(message)) { if (message.contains("<TranStat>1</TranStat>")) { return true; } else { System.out.println("error=" + message); } } return false; }
Example 17
Project: CowsEye-master File: SubmissionEvent.java View source code |
public MultipartEntity makeEntity() {
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
JSONObject jsonObject;
try {
//convert data to JSON
jsonObject = makeJSONFromSubmissionData();
Log.i(toString(), "Incident as JSON: " + jsonObject.toString());
} catch (JSONException e) {
Log.e(toString(), "JSONException: " + e);
return null;
}
try {
//add image data
String imagePath = imageToPath.toString();
if (fromGallery)
imagePath = myApplication.getRealPathFromURI(imageToPath);
reqEntity.addPart(Constants.FORM_POST_IMAGE, new FileBody(new File(imagePath)));
//add Data in JSON format
reqEntity.addPart(Constants.FORM_POST_DATA, new StringBody(jsonObject.toString()));
} catch (UnsupportedEncodingException e1) {
Log.e(toString(), "UnsupportedEncodingException : " + e1);
}
return reqEntity;
}
Example 18
Project: Eggscraper-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 19
Project: Eisenheinrich-master File: AsyncPoster.java View source code |
public void run() { httpClient.getParams().setParameter("http.protocol.handle-redirects", false); httpClient.getParams().setParameter("http.protocol.content-charset", CHARSETNAME); HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000); HttpContext localContext = new BasicHttpContext(); HttpPost httppost = new HttpPost(Defaults.POST_URL); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("desuchan.komturcode", globs.getKomturCode()); cookie.setDomain(defaults.DOMAIN); cookie.setPath("/"); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); try { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, CHARSET); // Bernd name entity.addPart(// Bernd name "internal_n", // Bernd name new StringBody(postVars.posterName, CHARSET)); // Post subject entity.addPart("internal_s", new StringBody(postVars.title, CHARSET)); entity.addPart("internal_t", new // Comment StringBody(// Comment postVars.content, // Comment CHARSET)); if (postVars.sage) // Säge entity.addPart(// Säge "sage", // Säge new StringBody("1")); // forward to thread or board -> thread for us entity.addPart("forward", new StringBody("thread")); entity.addPart("board", new // board StringBody(// board postVars.boardName, // board CHARSET)); if (null != postVars.threadNumber) { entity.addPart("parent", new StringBody(// thread ID postVars.threadNumber)); } if (null != postVars.files) { for (int i = 0; i < postVars.files.length; i++) { if (postVars.files[i] != null) { File f = new File(new URI(postVars.files[i].toString())); if (!f.exists()) { System.out.println(f.getAbsolutePath()); } entity.addPart(f.getName(), new FileBody(f)); } } } httppost.setEntity(entity); HttpResponse response = httpClient.execute(httppost, localContext); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() == 302) { //System.out.println (sl); Header headers[] = response.getAllHeaders(); String location = null; for (Header h : headers) { if (h.getName().equals("Location")) { location = h.getValue(); } //System.out.println (h.getName()+" "+h.getValue()); } if ((null != location) && (location.startsWith("/banned"))) { notifyPeers(false, Eisenheinrich.getInstance().getString(R.string.banned_message)); } else { notifyPeers(true, null); } } if (response.getEntity() != null) { response.getEntity().consumeContent(); } } catch (Exception e) { notifyPeers(false, "Failed in postInThread() - " + e.getMessage()); Log.e(TAG, "Failed in postInThread()", e); } }
Example 20
Project: felix-master File: UploadTest.java View source code |
private static void postContent(final char c, final long length, final int expectedRT) throws IOException { final URL url = createURL(PATH); final CloseableHttpClient httpclient = HttpClients.createDefault(); try { final HttpPost httppost = new HttpPost(url.toExternalForm()); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(c); } final StringBody text = new StringBody(sb.toString(), ContentType.TEXT_PLAIN); final HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("text", text).build(); httppost.setEntity(reqEntity); final CloseableHttpResponse response = httpclient.execute(httppost); try { final HttpEntity resEntity = response.getEntity(); EntityUtils.consume(resEntity); assertEquals(expectedRT, response.getStatusLine().getStatusCode()); } finally { response.close(); } } finally { httpclient.close(); } }
Example 21
Project: GeekBand-Android-1501-Homework-master File: NetUtil.java View source code |
/**
*
*
* @param url
* @param param
* @param file
* @return
* @throws Exception
*/
public static String doPost(String url, Map<String, String> param, File file) throws Exception {
HttpPost post = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
MultipartEntity entity = new MultipartEntity();
if (param != null && !param.isEmpty()) {
for (Map.Entry<String, String> entry : param.entrySet()) {
entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
}
}
// æ·»åŠ æ–‡ä»¶å?‚æ•°
if (file != null && file.exists()) {
entity.addPart("file", new FileBody(file));
}
post.setEntity(entity);
HttpResponse response = client.execute(post);
int stateCode = response.getStatusLine().getStatusCode();
StringBuffer sb = new StringBuffer();
if (stateCode == HttpStatus.SC_OK) {
HttpEntity result = response.getEntity();
if (result != null) {
InputStream is = result.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String tempLine;
while ((tempLine = br.readLine()) != null) {
sb.append(tempLine);
}
}
}
post.abort();
return sb.toString();
}
Example 22
Project: geni-openflow-vertical-handover-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } }
Example 23
Project: GeoRedTSI2-master File: ServicioRestImagenes.java View source code |
private static HttpResponse rest(Metodos metodo, String url, byte[] content, Boolean secure) { try { HttpPost request = new HttpPost(url); if (content != null) { File tmpUpload = File.createTempFile("tmpUpload", "jpg"); FileOutputStream outputStream = new FileOutputStream(tmpUpload); outputStream.write(content); outputStream.close(); FileBody bin = new FileBody(tmpUpload); StringBody header = new StringBody("upload-file"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("header", header); reqEntity.addPart("payload", bin); request.setEntity(reqEntity); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(request); return response; } if (request != null) { if (secure) request.addHeader(SECURITY_HEADER, getSecurityToken()); HttpClient cliente = new DefaultHttpClient(); HttpResponse response; response = cliente.execute(request, new BasicHttpContext()); return response; } } catch (ClientProtocolException e) { Log.e("Error", "URI syntax was incorrect.", e); e.printStackTrace(); } catch (IOException e) { Log.e("Error", "There was a problem when sending the request.", e); e.printStackTrace(); } return null; }
Example 24
Project: Gw2InfoViewer-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 25
Project: Hancel-master File: HockeySender.java View source code |
@Override public void send(CrashReportData report) throws ReportSenderException { try { System.setProperty("http.keepAlive", "false"); HttpClient httpclient = new DefaultHttpClient(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); final HttpParams par = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(par, HTTP_TIMEOUT); HttpConnectionParams.setSoTimeout(par, HTTP_TIMEOUT); ConnManagerParams.setTimeout(par, HTTP_TIMEOUT); HttpPost httppost; BeanDatosLog bean = new BeanDatosLog(); try { Process process = Runtime.getRuntime().exec("logcat -d"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder log = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { log.append(line); } // Log.d("******sdfwds", log+""); httppost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); entity.addPart("modelo", new StringBody(bean.getMarcaCel() + "")); entity.addPart("version", new StringBody(bean.getVersionAndroid() + "")); entity.addPart("tag", new StringBody(bean.getTagLog() + "")); entity.addPart("descripcion", new StringBody(log.toString() + "")); Log.d("******sdfwds", "enviado"); System.setProperty("http.keepAlive", "false"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
Example 26
Project: HRT-Log-Capture-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 27
Project: httpmime-master File: TestMultipartFormHttpEntity.java View source code |
@Test public void testRepeatable() throws Exception { MultipartEntity entity = new MultipartEntity(); entity.addPart("p1", new StringBody("blah blah")); entity.addPart("p2", new StringBody("yada yada")); Assert.assertTrue(entity.isRepeatable()); Assert.assertFalse(entity.isChunked()); Assert.assertFalse(entity.isStreaming()); long len = entity.getContentLength(); Assert.assertTrue(len == entity.getContentLength()); ByteArrayOutputStream out = new ByteArrayOutputStream(); entity.writeTo(out); out.close(); byte[] bytes = out.toByteArray(); Assert.assertNotNull(bytes); Assert.assertTrue(bytes.length == len); Assert.assertTrue(len == entity.getContentLength()); out = new ByteArrayOutputStream(); entity.writeTo(out); out.close(); bytes = out.toByteArray(); Assert.assertNotNull(bytes); Assert.assertTrue(bytes.length == len); }
Example 28
Project: hwbotprime-master File: SubmitCommentTask.java View source code |
@Override
public Void doInBackground(Void... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection * 1000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
// Create a response handler
String token;
if (SecurityService.getInstance().isLoggedIn()) {
token = SecurityService.getInstance().getCredentials().getToken();
} else {
token = "";
}
String uri = BenchService.SERVER + "/api/comment/" + target + "/" + targetId + "?securityToken=" + token;
Log.i(this.getClass().getSimpleName(), "Posting comment to " + uri + " with text: " + comment);
HttpPost req = new HttpPost(uri);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("text", new StringBody(comment));
req.setEntity(mpEntity);
BasicResponseStatusHandler responseHandler = new BasicResponseStatusHandler();
String response = httpclient.execute(req, responseHandler);
Log.i(this.getClass().getSimpleName(), "Response: " + response);
GenericApiResponse apiResponse = new Gson().fromJson(response, GenericApiResponse.class);
Log.i(this.getClass().getSimpleName(), "Response: " + apiResponse);
observer.notifyCommentSucceeded(icon, count);
} catch (UnknownHostException e) {
Log.w(this.getClass().getSimpleName(), "No network access: " + e.getMessage());
observer.notifyCommentFailed(icon);
} catch (HttpHostConnectException e) {
Log.i(this.getClass().getName(), "Failed to connect to HWBOT server! Are you connected to the internet?");
e.printStackTrace();
observer.notifyCommentFailed(icon);
} catch (Exception e) {
Log.i(this.getClass().getName(), "Error communicating with online service. If this issue persists, please contact HWBOT crew. Error: " + e.getMessage());
e.printStackTrace();
observer.notifyCommentFailed(icon);
} finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}
Example 29
Project: InterMine-Client-Scala-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 30
Project: java-client-library-master File: RepositoryFileUploadCall.java View source code |
/** * Internal use only, to execute call use RClient.execute(). */ public RCoreResult call() { RCoreResultImpl pResult = null; try { HttpPost httpPost = new HttpPost(serverUrl + API); super.httpUriRequest = httpPost; List<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("format", "json")); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip")); if (options.filename != null) entity.addPart("filename", new StringBody(options.filename, "text/plain", Charset.forName("UTF-8"))); if (options.directory != null) entity.addPart("directory", new StringBody(options.directory, "text/plain", Charset.forName("UTF-8"))); if (options.descr != null) entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8"))); entity.addPart("newversion", new StringBody(Boolean.toString(options.newversion), "text/plain", Charset.forName("UTF-8"))); if (options.newversionmsg != null) entity.addPart("newversionmsg", new StringBody(options.newversionmsg, "text/plain", Charset.forName("UTF-8"))); if (options.restricted != null) entity.addPart("restricted", new StringBody(options.restricted, "text/plain", Charset.forName("UTF-8"))); entity.addPart("shared", new StringBody(Boolean.toString(options.shared), "text/plain", Charset.forName("UTF-8"))); entity.addPart("published", new StringBody(Boolean.toString(options.published), "text/plain", Charset.forName("UTF-8"))); if (options.inputs != null) entity.addPart("inputs", new StringBody(options.inputs, "text/plain", Charset.forName("UTF-8"))); if (options.outputs != null) entity.addPart("outputs", new StringBody(options.outputs, "text/plain", Charset.forName("UTF-8"))); entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8"))); httpPost.setEntity(entity); // set any custom headers on the request for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } HttpResponse response = httpClient.execute(httpPost); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); String markup = EntityUtils.toString(responseEntity); pResult = new RCoreResultImpl(response.getAllHeaders()); pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase()); } catch (UnsupportedEncodingException ueex) { log.warn("RepositoryFileUploadCall: unsupported encoding exception.", ueex); } catch (IOException ioex) { log.warn("RepositoryFileUploadCall: io exception.", ioex); } return pResult; }
Example 31
Project: Kubach-master File: UploadSkinWorker.java View source code |
private void uploadSkinFile(String url) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(url); FileBody skin = new FileBody(skinFile); StringBody user = new StringBody(this.username, ContentType.TEXT_PLAIN); StringBody session = new StringBody(this.session, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("skinfile", skin).addPart("user", user).addPart("sessionId", session).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String resString = EntityUtils.toString(resEntity); if (resString.equals("OK")) { publish(new SkinUploadState(true)); } else { System.err.println("[Skin Upload Error] " + resString); publish(new SkinUploadState(false)); } } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } }
Example 32
Project: loli.io-master File: ImageCloudAPI.java View source code |
@Override public String upload(File fileToUpload) throws UploadException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost hp = new HttpPost(UPLOAD_URL); CloseableHttpResponse response = null; String result = null; String token = config.getImageCloudConfig().getToken(); String email = config.getImageCloudConfig().getEmail(); try { MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create(); multiPartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // �以直接addBinary multiPartEntityBuilder.addPart("image", new FileBody(fileToUpload, ContentType.create("image/png", Consts.UTF_8), fileToUpload.getName())); multiPartEntityBuilder.setCharset(Consts.UTF_8); // �以直接addText multiPartEntityBuilder.addPart("token", new StringBody(token, ContentType.create("text/plain", Consts.UTF_8))); multiPartEntityBuilder.addPart("email", new StringBody(email, ContentType.create("text/plain", Consts.UTF_8))); multiPartEntityBuilder.addPart("desc", new StringBody(fileToUpload.getName(), ContentType.create("text/plain", Consts.UTF_8))); hp.setEntity(multiPartEntityBuilder.build()); response = httpclient.execute(hp); result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { throw new UploadException(e); } System.out.println(result); JSONObject obj = new JSONObject(result); return "http://r.loli.io/" + obj.getString("redirectCode"); }
Example 33
Project: monkeytalk-master File: MultipartTest.java View source code |
@Test public void testMultipart() throws IOException, JSONException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/"); File image = new File("resources/test/base.png"); FileBody imagePart = new FileBody(image); StringBody messagePart = new StringBody("some message"); MultipartEntity req = new MultipartEntity(); req.addPart("image", imagePart); req.addPart("message", messagePart); httppost.setEntity(req); ImageEchoServer server = new ImageEchoServer(PORT); HttpResponse response = httpclient.execute(httppost); server.stop(); HttpEntity resp = response.getEntity(); assertThat(resp.getContentType().getValue(), is("application/json")); // sweet one-liner to convert an inputstream to a string from stackoverflow: // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string String out = new Scanner(resp.getContent()).useDelimiter("\\A").next(); JSONObject json = new JSONObject(out); String base64 = Base64.encodeFromFile("resources/test/base.png"); assertThat(json.getString("screenshot"), is(base64)); assertThat(json.getBoolean("imageEcho"), is(true)); }
Example 34
Project: One-Button-App---Android-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 35
Project: One-Button-App-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 36
Project: OpenMEAP-master File: FileHandlingHttpRequestExecuterImpl.java View source code |
@Override
public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException {
// test to determine whether this is a file upload or not.
Boolean isFileUpload = false;
for (Object o : postParams.values()) {
if (o instanceof File) {
isFileUpload = true;
break;
}
}
if (isFileUpload) {
try {
HttpPost httpPost = new HttpPost(createUrl(url, getParams));
httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Object o : postParams.entrySet()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o;
if (entry.getValue() instanceof File) {
// For File parameters
File file = (File) entry.getValue();
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(file.toURL().toString());
entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type));
} else {
// For usual String parameters
entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT)));
}
}
httpPost.setEntity(entity);
return execute(httpPost);
} catch (Exception e) {
throw new HttpRequestException(e);
}
} else {
return super.postData(url, getParams, postParams);
}
}
Example 37
Project: openmicroscopy-master File: MessengerFileRequest.java View source code |
/** * Prepares the <code>method</code> to post. * @see Request#marshal(String) */ public HttpUriRequest marshal(String path) throws TransportException { //Create request. MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(FILE, new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName())); builder.addPart(TOKEN, new StringBody(token, ContentType.TEXT_PLAIN)); builder.addPart(READER, new StringBody(reader, ContentType.TEXT_PLAIN)); HttpPost request = new HttpPost(path); request.setEntity(builder.build()); return request; }
Example 38
Project: opentrader.github.com-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 39
Project: PersonalityExtraction-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } if (resEntity != null) { resEntity.consumeContent(); } }
Example 40
Project: ps-scripts-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 41
Project: quhao-master File: CommantUtil.java View source code |
/**
* Ìá½»²ÎÊýÀïÓÐÎļþµÄÊý¾Ý
* @param url ·þÎñÆ÷µØÖ·
* @param param ²ÎÊý
* @return ·þÎñÆ÷·µ»Ø½á¹û
* @throws Exception
*/
//·¢Ë͸öÈËÍ·Ïñ
public static String uploadSubmit(String url, Map<String, String> param, File file, String uploadName) {
String httpUrl = QuhaoConstant.HTTP_URL + url;
// String httpUrl = "http://192.168.1.100:9081/" + url;
StringBuffer sb = null;
InputStream is = null;
BufferedReader br = null;
try {
HttpPost post = new HttpPost(httpUrl);
post.setHeader("user-agent", "QuhaoAndroid");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 60 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout in milliseconds which is the timeout
// for waiting for data.
int timeoutSocket = 60 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
MultipartEntity entity = new MultipartEntity();
if (param != null && !param.isEmpty()) {
for (Map.Entry<String, String> entry : param.entrySet()) {
if (entry.getValue() != null && entry.getValue().trim().length() > 0) {
entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName(org.apache.http.protocol.HTTP.UTF_8)));
}
}
}
// Ìí¼ÓÎļþ²ÎÊý
if (file != null && file.exists()) {
entity.addPart(uploadName, new FileBody(file));
}
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int stateCode = response.getStatusLine().getStatusCode();
sb = new StringBuffer();
if (stateCode == HttpStatus.SC_OK) {
HttpEntity result = response.getEntity();
if (result != null) {
is = result.getContent();
br = new BufferedReader(new InputStreamReader(is));
String tempLine;
while ((tempLine = br.readLine()) != null) {
sb.append(tempLine);
}
}
}
post.abort();
return sb.toString();
} catch (Exception e) {
Log.e("", e.getMessage());
return "error";
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Example 42
Project: sana.mobile-master File: HttpRequestBuilder.java View source code |
@Override
public HttpUriRequest produceCreate(URI uri, Map<String, ?> formData, Map<String, URI> files) throws UnsupportedEncodingException {
HttpPost request = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity();
if (files != null) {
for (String key : files.keySet()) {
URI value = files.get(key);
entity.addPart(key, new FileBody(new File(value)));
}
}
if (formData != null) {
for (String key : formData.keySet()) {
Object value = formData.get(key);
entity.addPart(key, new StringBody(String.valueOf(value)));
}
}
request.setEntity(entity);
return request;
}
Example 43
Project: semantictools-master File: AppspotContextPublisher.java View source code |
@Override public void publish(LdAsset asset) throws LdPublishException { String uri = asset.getURI(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(SERVLET_URL); post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx", Charset.forName("UTF-8")); try { String content = asset.loadContent(); entity.addPart(URI, new StringBody(uri)); entity.addPart(FILE_UPLOAD, new StringBody(content)); post.setEntity(entity); logger.debug("uploading... " + uri); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); client.getConnectionManager().shutdown(); if (status != HttpURLConnection.HTTP_OK) { throw new LdPublishException(uri, null); } } catch (Exception e) { throw new LdPublishException(uri, e); } }
Example 44
Project: Surviving-with-android-master File: UploadActivity.java View source code |
@Override protected String doInBackground(String... params) { String url = params[0]; String param1 = params[1]; String param2 = params[2]; try { Bitmap b = BitmapFactory.decodeResource(UploadActivity.this.getResources(), R.drawable.logo); ByteArrayOutputStream baos = new ByteArrayOutputStream(); b.compress(CompressFormat.PNG, 0, baos); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); MultipartEntity multiPart = new MultipartEntity(); multiPart.addPart("param1", new StringBody(param1)); multiPart.addPart("param2", new StringBody(param2)); multiPart.addPart("file", new ByteArrayBody(baos.toByteArray(), "logo.png")); post.setEntity(multiPart); client.execute(post); } catch (Throwable t) { t.printStackTrace(); } return null; }
Example 45
Project: unirest-android-master File: MultipartBody.java View source code |
public HttpEntity getEntity() {
if (hasFile) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Entry<String, Object> part : parameters.entrySet()) {
Object value = part.getValue();
if (null == value)
continue;
if (value instanceof File) {
hasFile = true;
builder.addPart(part.getKey(), new FileBody((File) value));
} else {
builder.addPart(part.getKey(), new StringBody(value.toString(), ContentType.APPLICATION_FORM_URLENCODED));
}
}
return builder.build();
} else {
try {
return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
Example 46
Project: uploadcare-java-master File: FileUploader.java View source code |
/** * Synchronously uploads the file to Uploadcare. * * The calling thread will be busy until the upload is finished. * * @return An Uploadcare file */ public File upload() throws UploadFailureException { URI uploadUrl = Urls.uploadBase(); HttpPost request = new HttpPost(uploadUrl); MultipartEntity entity = new MultipartEntity(); StringBody pubKeyBody = StringBody.create(client.getPublicKey(), "text/plain", null); StringBody storeBody = StringBody.create(store, "text/plain", null); entity.addPart("UPLOADCARE_PUB_KEY", pubKeyBody); entity.addPart("UPLOADCARE_STORE", storeBody); if (file != null) { entity.addPart("file", new FileBody(file)); } else { entity.addPart("file", new ByteArrayBody(bytes, filename)); } request.setEntity(entity); String fileId = client.getRequestHelper().executeQuery(request, false, UploadBaseData.class).file; return client.getFile(fileId); }
Example 47
Project: uw-android-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } }
Example 48
Project: YikuairAndroid-master File: UploadFileUtil.java View source code |
@Override public void run() { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(UserInfo.uploadRequestUrl); MultipartEntity mpEntity = new MultipartEntity(); Log.e("test", "uploadPath :" + uploadPath); FileBody file = new FileBody(new File(uploadPath), "application/octet-stream", uploadPath); Log.i("test", "name :" + UserInfo.id); Log.i("test", "receiver : " + receiver); Log.i("test", "msguuid : " + msguuid); Log.i("test", "type :" + String.valueOf(fileType)); Log.i("test", "path :" + uploadPath); mpEntity.addPart("upload", file); mpEntity.addPart("username", new StringBody(UserInfo.id)); mpEntity.addPart("token", new StringBody(String.valueOf(fileType))); mpEntity.addPart("from", new StringBody(UserInfo.db_id)); mpEntity.addPart("to", new StringBody(receiver)); int type = 0; if (chatType == MessageInfo.INDIVIDUAL) type = 1; else if (chatType == MessageInfo.GROUP) type = 2; mpEntity.addPart("type", new StringBody(String.valueOf(type))); mpEntity.addPart("msguuid", new StringBody(msguuid)); mpEntity.addPart("password", new StringBody(UserInfo.cipher_password)); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); String content = EntityUtils.toString(response.getEntity()); Message msg = mHandler.obtainMessage(); msg.obj = content; msg.sendToTarget(); httpclient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } }
Example 49
Project: zeitgeist-api-master File: ClientMultipartFormPost.java View source code |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 50
Project: AndRoad-master File: OSBRequestComposer.java View source code |
// =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * * -- To add a bug -- * <pre> * Make a POST request on : * http://openstreetbugs.appspot.com/addPOIexec * with : * lat (float) * lon (float) * text (string/utf-8) * * You should get a response with : * ok\n * idOfTheNewBug * </pre> * @param pBugGeoPoint * @param pBugDescription * @return */ public static MultipartEntity createSubmitBugEntitiy(final GeoPoint pBugGeoPoint, final String pBugDescription) { final MultipartEntity out = new MultipartEntity(); try { out.addPart("lat", new StringBody(String.valueOf(pBugGeoPoint.getLatitudeE6() / 1E6))); out.addPart("lon", new StringBody(String.valueOf(pBugGeoPoint.getLongitudeE6() / 1E6))); out.addPart("text", new StringBody(pBugDescription, Charset.forName("UTF-8"))); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); } return out; }
Example 51
Project: android-stream-file-upload-master File: FileUploadFacadeTest.java View source code |
@Test
public void post2() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException {
final FileUploadFacadeTestClass fileUploadFacadeTestClass = new FileUploadFacadeTestClass();
fileUploadFacadeTestClass.post(URL, FILE, PARAMS, new FileUploadCallback() {
public void onSuccess(int statusCode, String response) {
mRequest = fileUploadFacadeTestClass.request;
}
public void onFailure(int statusCode, String response, Throwable e) {
}
});
await().until(isSetHttpUriRequest());
assert (mRequest instanceof HttpPost);
assertEquals(URL, mRequest.getURI().toString());
Map<String, ContentBody> parts = getBodyMap(mRequest);
assertEquals(FILE, ((FileBody) parts.get("file")).getFile());
assertEquals("value", stringBodyToString((StringBody) parts.get("key")));
}
Example 52
Project: AndroidProjectStroe-master File: AddHttpMultipartPost.java View source code |
@Override protected String doInBackground(String... params) { String serverResponse = ""; HttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(actionUrl); upToServer(bundle, bean, photoDisplayBlock, pic_sort); try { MyMultipartEntity multipartContent = new MyMultipartEntity(new ProgressListener() { @Override public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); if (params != null && !postParams.isEmpty()) { for (Map.Entry<String, String> entry : postParams.entrySet()) { StringBody par = null; try { if (entry.getValue() == null) { continue; } par = new StringBody(java.net.URLEncoder.encode(entry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } multipartContent.addPart(entry.getKey(), par); } } for (int i = 0; i < photoDisplayBlock.getPhotos().size(); i++) { FileBody file = new FileBody(new File(photoDisplayBlock.getPhotos().get(i).getPath())); multipartContent.addPart("imageFile", file); } // We use FileBody to transfer an image totalSize = multipartContent.getContentLength(); // Send it httpPost.setEntity(multipartContent); HttpResponse response = httpClient.execute(httpPost, httpContext); int res = response.getStatusLine().getStatusCode(); Log.e("å›¾ç‰‡ä¸Šä¼ è¿”å›žç›¸åº”ç ?", res + ","); switch(res) { case 200: serverResponse = "æ•°æ?®ä¸Šä¼ æˆ?功"; break; case 404: serverResponse = "æ•°æ?®ä¸Šä¼ 失败,请é‡?试"; break; default: serverResponse = "æ•°æ?®ä¸Šä¼ 失败,请é‡?试"; } // } catch (Exception e) { serverResponse = "æ•°æ?®ä¸Šä¼ 失败,请é‡?试"; e.printStackTrace(); } return serverResponse; }
Example 53
Project: AndroidSDK-RecipeBook-master File: Recipe095.java View source code |
// 指定ã?•ã‚Œã?ŸUriã?®å†™çœŸã‚’Tumblrã?«ã‚¢ãƒƒãƒ—ãƒãƒ¼ãƒ‰ã?—ã?¾ã?™ã€‚ private void uploadForTumblr(Uri uri) { // HTTPクライアントを作ã?£ã?¦ HttpClient client = new DefaultHttpClient(); // POSTå…ˆã?®URLを指定ã?—ã?¦POSTオブジェクトを作ã?£ã?¦ HttpPost post = new HttpPost("http://www.tumblr.com/api/write"); // パラメータを作ã?£ã?¦ MultipartEntity entity = new MultipartEntity(); try { // Thumblrã?«ç™»éŒ²ã?—ã?Ÿãƒ¡ãƒ¼ãƒ«ã‚¢ãƒ‰ãƒ¬ã‚¹ entity.addPart("email", new StringBody("hoge@example.com")); // Thumblrã?«ç™»éŒ²ã?—ã?Ÿãƒ‘スワード entity.addPart("password", new StringBody("1234")); // 投稿ã?™ã‚‹ç¨®é¡žã€‚今回ã?¯å†™çœŸã?ªã?®ã?§photo entity.addPart("type", new StringBody("photo")); // 写真データ entity.addPart("data", new InputStreamBody(getContentResolver().openInputStream(uri), "filename")); // POSTオブジェクトã?«ãƒ‘ラメータをセット post.setEntity(entity); // POSTリクエストを実行 client.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Example 54
Project: argouml-master File: GATEHelper.java View source code |
public static void upload(String taskID, String sessionID, File file, String fileExtension, List<Integer> selectedPartners) throws ClientProtocolException, IOException, InterruptedException {
URL gateURL = null;
try {
gateURL = new URL(Main.servletPath);
} catch (MalformedURLException e) {
}
DefaultHttpClient client = new DefaultHttpClient();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", sessionID);
cookie.setPath("/");
cookie.setVersion(1);
cookie.setDomain(gateURL.getHost());
if (gateURL.getProtocol().equals("https"))
cookie.setSecure(true);
client.getCookieStore().addCookie(cookie);
HttpPost post = new HttpPost(Main.servletPath + "/SubmitSolution?taskid=" + taskID);
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity reqEntity2 = new MultipartEntity();
for (Integer partnerID : selectedPartners) {
reqEntity2.addPart("partnerid", new StringBody(String.valueOf(partnerID)));
}
FileBody bin = null;
if (fileExtension.equals("png")) {
bin = new FileBody(file, "loesung." + fileExtension, "image/png", "utf-8");
} else {
bin = new FileBody(file, "loesung." + fileExtension, "text/xml", "utf-8");
}
// FileBody bin = new FileBody(file);
reqEntity2.addPart("file", bin);
post.setEntity(reqEntity2);
System.out.println("executing request " + post.getRequestLine());
HttpResponse response = client.execute(post);
if (response.getFirstHeader("SID") != null) {
Main.sID = response.getFirstHeader("SID").getValue();
} else {
throw new IOException("got no SID");
}
if (response.getFirstHeader("TID") != null)
Main.testID = response.getFirstHeader("TID").getValue();
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Example 55
Project: browsermob-proxy-master File: BrowserMobHttpRequest.java View source code |
public BrowserMobHttpResponse execute() {
// deal with PUT/POST requests
if (method instanceof HttpEntityEnclosingRequestBase) {
HttpEntityEnclosingRequestBase enclodingRequest = (HttpEntityEnclosingRequestBase) method;
if (!nvps.isEmpty()) {
try {
if (!multiPart) {
enclodingRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} else {
for (NameValuePair nvp : nvps) {
multipartEntity.addPart(nvp.getName(), new StringBody(nvp.getValue()));
}
enclodingRequest.setEntity(multipartEntity);
}
} catch (UnsupportedEncodingException e) {
LOG.severe("Could not find UTF-8 encoding, something is really wrong", e);
}
} else if (multipartEntity != null) {
enclodingRequest.setEntity(multipartEntity);
} else if (byteArrayEntity != null) {
enclodingRequest.setEntity(byteArrayEntity);
} else if (stringEntity != null) {
enclodingRequest.setEntity(stringEntity);
} else if (inputStreamEntity != null) {
enclodingRequest.setEntity(inputStreamEntity);
}
}
return client.execute(this);
}
Example 56
Project: CanvasAPI-master File: KalturaAPI.java View source code |
///////////////////////////////////////////////////////////////////////////// // Synchronous // // If Retrofit is unable to parse (no network for example) Synchronous calls // will throw a nullPointer exception. All synchronous calls need to be in a // try catch block. ///////////////////////////////////////////////////////////////////////////// public static xml uploadFileAtPathSynchronous(String uploadToken, Uri fileUri, Context context) { if (context == null) { return null; } try { //Get needed vars String kalturaToken = APIHelpers.getKalturaToken(context); String baseUrl = APIHelpers.getFullKalturaDomain(context); File file = new File(fileUri.getPath()); String fileType = FileUtilities.getMimeType(fileUri.getPath()); String boundary = "---------------------------3klfenalksjflkjoi9auf89eshajsnl3kjnwal"; //Build URL String fullUrl = baseUrl + "/api_v3/index.php?service=uploadtoken&action=upload"; HttpPost post = new HttpPost(fullUrl); //Add info to body MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, boundary, null); entity.addPart("ks", new StringBody(kalturaToken)); entity.addPart("uploadTokenId", new StringBody(uploadToken)); ContentType contentType = ContentType.create(fileType); entity.addPart("fileData", new FileBody(file, contentType, file.getName())); post.setEntity(entity); //Send request HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(post); //Check that It worked. String stringResponse = EntityUtils.toString(response.getEntity()); if (stringResponse.contains("error")) { return null; } return getMediaIdForUploadedFileTokenSynchronous(context, kalturaToken, uploadToken, file.getName(), fileType); } catch (Exception e) { Log.e(APIHelpers.LOG_TAG, e.toString()); return null; } }
Example 57
Project: ChildShareClient-master File: PhotoUploadActivity.java View source code |
private void uploadFile1() { HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost(Url.DOMAIN_URL + "child_share/ImageServlet?cmd=add"); FileBody bin = new FileBody(new File(imagePath)); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("description", new StringBody(URLEncoder.encode(description.getText().toString(), "UTF-8"))); reqEntity.addPart("userId", new StringBody(URLEncoder.encode("jeffreyzhang", "UTF-8"))); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } } catch (Exception e) { System.out.println("ä¸Šä¼ å¤±è´¥...."); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 58
Project: citizen-complaint-master File: CitizenComplaintHttpUtil.java View source code |
public static void postComplaintDetails(Context context, CitizenComplaint citizenComplaint) { try { if (CitizenComplaintUtility.isDeviceOnline(context)) { HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httppost = new HttpPost(CitizenComplaintConstants.CITIZEN_COMPLAINT_POST_URL_PARAMS); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart(CitizenComplaintConstants.LATTITUDE_PARAMS, new StringBody("" + citizenComplaint.getLatitude())); multipartEntity.addPart(CitizenComplaintConstants.LONGITUDE_PARAMS, new StringBody("" + citizenComplaint.getLongitude())); multipartEntity.addPart(CitizenComplaintConstants.ISSUE_TYPE_PARAMS, new StringBody("" + citizenComplaint.getComplaintId())); multipartEntity.addPart(CitizenComplaintConstants.TEMPLATE_ID_PARAMS, new StringBody("" + citizenComplaint.getSelectedTemplateId())); multipartEntity.addPart(CitizenComplaintConstants.TEMPLATE_TEXT_PARAMS, new StringBody("" + citizenComplaint.getSelectedTemplateString())); multipartEntity.addPart(CitizenComplaintConstants.REPORTER_ID_PARAMS, new StringBody("" + CitizenComplaintUtility.getDeviceIdentifier(context))); multipartEntity.addPart(CitizenComplaintConstants.ADDRESS_PARAMS, new StringBody("" + citizenComplaint.getComplaintAddress())); if (citizenComplaint.getSelectedComplaintImageUri() != null && !citizenComplaint.getSelectedComplaintImageUri().equals("")) { File file = new File(citizenComplaint.getSelectedComplaintImageUri()); if (file.exists()) { multipartEntity.addPart(CitizenComplaintConstants.IMAGE_URI_PARAMS, new FileBody(file)); } } if (citizenComplaint.getProfileThumbnailImageUri() != null && !citizenComplaint.getProfileThumbnailImageUri().equals("")) { File file = new File(citizenComplaint.getProfileThumbnailImageUri()); if (file.exists()) { multipartEntity.addPart(CitizenComplaintConstants.PROFILE_IMAGE_URI_PARAMS, new FileBody(file)); } } httppost.setEntity(multipartEntity); httpClient.execute(httppost, new CitizenComplaintUploadResponseHandler()); CitizenComplaintDataSource.getInstance(context).deleteCitizenComplaint(citizenComplaint); } } catch (Exception e) { Log.e("Complaint Upload", "Complaint Upload exception: " + e.getMessage()); } }
Example 59
Project: commcare-master File: ForceCloseLogger.java View source code |
/** * Try to send the given data to the given uri * * @return If send was successful */ private static boolean sendErrorToServer(byte[] dataToSend, String submissionUri) { String payload = new String(dataToSend); Log.d(TAG, "Outgoing payload: " + payload); MultipartEntity entity = new MultipartEntity(); try { //Apparently if you don't have a filename in the multipart wrapper, some receivers //don't properly receive this post. StringBody body = new StringBody(payload, "text/xml", MIME.DEFAULT_CHARSET) { @Override public String getFilename() { return "exceptionreport.xml"; } }; entity.addPart("xml_submission_file", body); } catch (IllegalCharsetNameExceptionUnsupportedEncodingException | UnsupportedCharsetException | e1) { e1.printStackTrace(); return false; } HttpRequestGenerator generator; try { User user = CommCareApplication.instance().getSession().getLoggedInUser(); generator = new HttpRequestGenerator(user); } catch (Exception e) { generator = HttpRequestGenerator.buildNoAuthGenerator(); } try { HttpResponse response = generator.postData(submissionUri, entity); ByteArrayOutputStream bos = new ByteArrayOutputStream(); response.getEntity().writeTo(bos); Log.d(TAG, "Response: " + new String(bos.toByteArray())); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Example 60
Project: DeskBin-master File: ImgurService.java View source code |
@Override public String upload(File image) throws ImageServiceException { try { HttpPost post = new HttpPost(UPLOAD_URL); MultipartEntity entity = new MultipartEntity(); entity.addPart("key", new StringBody(apikey, Charset.forName("UTF-8"))); entity.addPart("type", new StringBody("file", Charset.forName("UTF-8"))); FileBody fileBody = new FileBody(image); entity.addPart("image", fileBody); post.setEntity(entity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { throw new ImageServiceException("Error accessing imgur. Status code: " + response.getStatusLine().getStatusCode()); } String json = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = new JSONObject(json).getJSONObject("upload").getJSONObject("links"); return jsonObject.getString("imgur_page"); } catch (Exception e) { throw new ImageServiceException(e); } }
Example 61
Project: evrythng-java-sdk-master File: HttpMethodBuilder.java View source code |
@Override public HttpPost build(final URI uri) throws EvrythngClientException { HttpPost request = new HttpPost(uri); MultipartEntity reqEntity = new MultipartEntity(); try { // Name of the file StringBody strBody = new StringBody(file.getName()); reqEntity.addPart("filename", strBody); // File attachment FileBody fileBody = new FileBody(file); reqEntity.addPart("file", fileBody); request.setEntity(reqEntity); } catch (UnsupportedEncodingException ex) { throw new EvrythngClientException("Unable to build the multipart post request", ex); } return request; }
Example 62
Project: extdirectspring-master File: FileUploadServiceTest.java View source code |
@Test public void testUpload() throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpPost post = new HttpPost("http://localhost:9998/controller/router"); InputStream is = getClass().getResourceAsStream("/UploadTestFile.txt"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt"); builder.addPart("fileUpload", cbFile); builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT)); builder.addPart("extAction", new StringBody("fileUploadService", ContentType.DEFAULT_TEXT)); builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT)); builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT)); builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT)); builder.addPart("name", new StringBody("Jimöäü", ContentType.create("text/plain", Charset.forName("UTF-8")))); builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT)); builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT)); builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT)); post.setEntity(builder.build()); response = client.execute(post); HttpEntity resEntity = response.getEntity(); assertThat(resEntity).isNotNull(); String responseString = EntityUtils.toString(resEntity); String prefix = "<html><body><textarea>"; String postfix = "</textarea></body></html>"; assertThat(responseString).startsWith(prefix); assertThat(responseString).endsWith(postfix); String json = responseString.substring(prefix.length(), responseString.length() - postfix.length()); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper.readValue(json, Map.class); assertThat(rootAsMap).hasSize(5); assertThat(rootAsMap.get("method")).isEqualTo("uploadTest"); assertThat(rootAsMap.get("type")).isEqualTo("rpc"); assertThat(rootAsMap.get("action")).isEqualTo("fileUploadService"); assertThat(rootAsMap.get("tid")).isEqualTo(2); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result"); assertThat(result).hasSize(7); assertThat(result.get("name")).isEqualTo("Jimöäü"); assertThat(result.get("firstName")).isEqualTo("Ralph"); assertThat(result.get("age")).isEqualTo(25); assertThat(result.get("e-mail")).isEqualTo("test@test.ch"); assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt"); assertThat(result.get("fileContents")).isEqualTo("contents of upload file"); assertThat(result.get("success")).isEqualTo(Boolean.TRUE); EntityUtils.consume(resEntity); is.close(); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
Example 63
Project: extentreports-java-master File: HttpMediaManager.java View source code |
@Override public void storeMedia(Media m) throws IOException { File f = new File(m.getPath()); if (!f.exists()) { throw new IOException("The system cannot find the file specified " + m.getPath()); } HttpPost post = new HttpPost(host + ROUTE); post.addHeader("X-CSRF-TOKEN", csrf); post.addHeader("Connection", "keep-alive"); post.addHeader("User-Agent", "Mozilla/5.0"); post.addHeader("Cookie", cookie); post.addHeader("Accept", "application/json"); String ext = FileUtil.getExtension(m.getPath()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("name", new StringBody(m.getSequence() + "." + ext, ContentType.TEXT_PLAIN)); builder.addPart("id", new StringBody(m.getObjectId().toString(), ContentType.TEXT_PLAIN)); builder.addPart("reportId", new StringBody(m.getReportObjectId().toString(), ContentType.TEXT_PLAIN)); builder.addPart("testId", new StringBody(m.getTestObjectId().toString(), ContentType.TEXT_PLAIN)); if (m.getLogObjectId() != null) builder.addPart("logId", new StringBody(m.getLogObjectId().toString(), ContentType.TEXT_PLAIN)); builder.addPart("mediaType", new StringBody(String.valueOf(m.getMediaType()).toLowerCase(), ContentType.TEXT_PLAIN)); builder.addPart("f", new FileBody(new File(m.getPath()))); post.setEntity(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); boolean isValid = isResponseValid(responseCode); if (!isValid) { logger.warning("Unable to upload file to server " + m.getPath()); } }
Example 64
Project: FanXin2.0_IM-master File: LoadDataFromServer.java View source code |
@SuppressWarnings("rawtypes") public void run() { HttpClient client = new DefaultHttpClient(); MultipartEntity entity = new MultipartEntity(); Set keys = map.keySet(); if (keys != null) { Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = (String) map.get(key); if (key.equals("file")) { File file = new File(value); entity.addPart(key, new FileBody(file)); } else { try { entity.addPart(key, new StringBody(value, Charset.forName("UTF-8"))); System.out.println("key---->>>>" + key + "------value---->>>>" + value); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Message msg = new Message(); msg.what = 222; msg.obj = null; handler.sendMessage(msg); } } } } // å?¯ä»¥å°†ä¼ 入自定义的键å??...... if (has_Array) { for (int i = 0; i < members.size(); i++) { try { entity.addPart("members[]", new StringBody(members.get(i), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { Message msg = new Message(); msg.what = 222; msg.obj = null; handler.sendMessage(msg); e.printStackTrace(); } } } client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); // 请求超时 client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000); HttpPost post = new HttpPost(url); post.setEntity(entity); StringBuilder builder = new StringBuilder(); try { HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8"))); for (String s = reader.readLine(); s != null; s = reader.readLine()) { builder.append(s); } String builder_BOM = jsonTokener(builder.toString()); System.out.println("返回数æ?®æ˜¯------->>>>>>>>" + builder.toString()); try { JSONObject jsonObject = new JSONObject(); jsonObject = JSONObject.parseObject(builder_BOM); Message msg = new Message(); msg.what = 111; msg.obj = jsonObject; handler.sendMessage(msg); } catch (JSONException e) { Message msg = new Message(); msg.what = 222; msg.obj = null; handler.sendMessage(msg); e.printStackTrace(); } } } catch (ClientProtocolException e) { Message msg = new Message(); msg.what = 222; msg.obj = null; handler.sendMessage(msg); e.printStackTrace(); } catch (IOException e) { Message msg = new Message(); msg.what = 222; msg.obj = null; handler.sendMessage(msg); e.printStackTrace(); } }
Example 65
Project: glaze-http-master File: FormHelper.java View source code |
private static void addStringBody(Object bean, MultipartEntity multipartEntity, Field field) { TextMultipart sa = field.getAnnotation(TextMultipart.class); if (sa != null) { try { field.setAccessible(true); StringBody body = new StringBody(field.get(bean).toString(), sa.mime(), Charset.forName(sa.charset())); multipartEntity.addPart(sa.name().isEmpty() ? field.getName() : sa.name(), body); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } finally { field.setAccessible(false); } } }
Example 66
Project: IndoorLocatorAndroidClient-master File: UploadImageTask.java View source code |
private static String uploadToSever(String url, List<NameValuePair> nameValuePairs) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++) {
if (nameValuePairs.get(index).getName().equalsIgnoreCase("filename")) {
builder.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue())));
} else {
builder.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity responseEntity = response.getEntity();
String strResponse = "";
if (responseEntity != null) {
strResponse = EntityUtils.toString(responseEntity);
}
return strResponse;
} catch (IOException e) {
throw e;
} finally {
httpPost = null;
httpClient = null;
}
}
Example 67
Project: jackrabbit-master File: Utils.java View source code |
/** * * @param paramName * @param value * @param resolver * @throws RepositoryException */ static void addPart(String paramName, QValue value, NamePathResolver resolver, List<FormBodyPart> parts, List<QValue> binaries) throws RepositoryException { FormBodyPartBuilder builder = FormBodyPartBuilder.create().setName(paramName); ContentType ctype = ContentType.create(JcrValueType.contentTypeFromType(value.getType()), DEFAULT_CHARSET); FormBodyPart part; switch(value.getType()) { case PropertyType.BINARY: binaries.add(value); part = builder.setBody(new InputStreamBody(value.getStream(), ctype)).build(); break; case PropertyType.NAME: part = builder.setBody(new StringBody(resolver.getJCRName(value.getName()), ctype)).build(); break; case PropertyType.PATH: part = builder.setBody(new StringBody(resolver.getJCRPath(value.getPath()), ctype)).build(); break; default: part = builder.setBody(new StringBody(value.getString(), ctype)).build(); } parts.add(part); }
Example 68
Project: LJPro-master File: FlickrAPI.java View source code |
public HashMap<String, String> uploadPhoto(String token, String title, String photopath) { params.put("api_key", mKey); params.put("auth_token", token); try { MultipartEntityMonitored postbody = new MultipartEntityMonitored(mContext, photopath, title); File photoFile = new File(photopath); postbody.addPart("photo", new FileBody(photoFile)); postbody.addPart("api_key", new StringBody(mKey)); postbody.addPart("auth_token", new StringBody(token)); if (!title.equals("")) { params.put("title", title); postbody.addPart("title", new StringBody(title)); } makeSignature(); postbody.addPart("api_sig", new StringBody(params.get("api_sig"))); String resp = doPost(UPLOAD_ENDPOINT, postbody); Matcher photomatch = photoID.matcher(resp); String photoid = null; if (photomatch.find()) { photoid = photomatch.group(); } makeEmptyParams(); params.put("method", "flickr.photos.getSizes"); params.put("auth_token", token); params.put("photo_id", photoid); makeSignature(); String httpresp = doGet(getURL(REST_ENDPOINT)); JSONObject json = parseJSONObject(httpresp); JSONArray sizes = json.getJSONObject("sizes").getJSONArray("size"); HashMap<String, String> photodata = new HashMap<String, String>(); int nSizes = sizes.length(); JSONObject size = sizes.getJSONObject(nSizes - 1); photodata.put("source", size.getString("source")); photodata.put("link", "http://flic.kr/p/" + FlickrBaseEncoder.encode(Long.parseLong(photoid))); return photodata; } catch (Throwable t) { Log.e("FLICKRUPLOAD", t.getMessage(), t); } return null; }
Example 69
Project: MyHeath-Android-master File: AbstractNetWorkThread.java View source code |
protected String executeMultipartPost(Bitmap bitmap, String filename, List<BasicNameValuePair> pairs) {
setUrl();
if (mUrl == null) {
return null;
}
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpPost mHttpPost = new HttpPost(mUrl);
mHttpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, TIMEOUT);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
HttpClientParams.setRedirecting(params, false);
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
}
mHttpClient.setParams(params);
ByteArrayBody bab = new ByteArrayBody(data, filename);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("photo", bab);
for (BasicNameValuePair item : pairs) {
reqEntity.addPart(item.getName(), new StringBody(item.getValue()));
}
mHttpPost.setEntity(reqEntity);
HttpResponse response = mHttpClient.execute(mHttpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Example 70
Project: Secure-Service-Specification-and-Deployment-master File: ActivitiEngineClient.java View source code |
public static String uploadDeployment(String filePath) throws ClientProtocolException, IOException { Properties prop = Activator.getConfigProperties(); // ResourceBundle config = ResourceBundle.getBundle("config"); String activitiEngineAddress = prop.getProperty("ActivitiEngineAddress"); URL url = new URL(activitiEngineAddress); String scheme = url.getProtocol(); String hostName = url.getHost(); int port = url.getPort(); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHost targetHost = new HttpHost(hostName, port, scheme); try { httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(prop.getProperty("ActivitiEngineUsername"), prop.getProperty("ActivitiEnginePassword"))); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpPost httppost = new HttpPost(activitiEngineAddress + "/activiti-rest/service/deployment"); FileBody bin = new FileBody(new File(filePath)); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("success", new StringBody("success", Charset.forName("UTF-8"))); reqEntity.addPart("failure", new StringBody("failure", Charset.forName("UTF-8"))); reqEntity.addPart("deployment", bin); httppost.setEntity(reqEntity); System.out.println("Executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost, localcontext); System.out.println("Response status: " + response.getStatusLine()); return response.getStatusLine().toString(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
Example 71
Project: smaph-erd-master File: ERDSystem.java View source code |
@Override public HashSet<Tag> solveC2W(String text) throws AnnotationException { lastTime = Calendar.getInstance().getTimeInMillis(); HashSet<Tag> res = new HashSet<Tag>(); try { URL erdApi = new URL(url); HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("runID", new StringBody(this.run)); multipartEntity.addPart("TextID", new StringBody("" + text.hashCode())); multipartEntity.addPart("Text", new StringBody(text)); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = ((HttpURLConnection) connection).getResponseCode(); if (status != 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String line = null; while ((line = br.readLine()) != null) System.err.println(line); throw new RuntimeException(); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = br.readLine()) != null) { String mid = line.split("\t")[2]; String title = freebApi.midToTitle(mid); int wid; if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1) System.err.println("Discarding mid=" + mid); else res.add(new Tag(wid)); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } lastTime = Calendar.getInstance().getTimeInMillis() - lastTime; return res; }
Example 72
Project: sonar-plugins-master File: MarkupValidator.java View source code |
/**
* Post contents of HTML file to the W3C validation service. In return, receive a Soap response message.
*
* @see http://validator.w3.org/docs/api.html
*/
private void postHtmlContents(InputFile inputfile) {
HttpPost post = new HttpPost(validationUrl);
HttpResponse response = null;
post.addHeader("User-Agent", "sonar-w3c-markup-validation-plugin/1.0");
try {
LOG.info("W3C Validate: " + inputfile.getRelativePath());
// file upload
MultipartEntity multiPartRequestEntity = new MultipartEntity();
String charset = CharsetDetector.detect(inputfile.getFile());
FileBody fileBody = new FileBody(inputfile.getFile(), TEXT_HTML_CONTENT_TYPE, charset);
multiPartRequestEntity.addPart(UPLOADED_FILE, fileBody);
// set output format
multiPartRequestEntity.addPart(OUTPUT, new StringBody(SOAP12));
post.setEntity(multiPartRequestEntity);
response = executePostMethod(post);
// write response to report file
if (response != null) {
writeResponse(response, inputfile);
}
} catch (UnsupportedEncodingException e) {
LOG.error(e);
} finally {
// release any connection resources used by the method
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException ioe) {
LOG.debug(ioe);
}
}
}
}
Example 73
Project: streamsx.topology-master File: RestUtils.java View source code |
/** * Submit an application bundle to execute as a job. */ public static JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle, JsonObject jobConfigOverlay) throws ClientProtocolException, IOException { final String serviceName = jstring(service, "name"); final JsonObject credentials = service.getAsJsonObject("credentials"); String url = getJobSubmitURL(credentials, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAPIKey(credentials)); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody).addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build(); postJobWithConfig.setEntity(reqEntity); JsonObject jsonResponse = getGsonResponse(httpClient, postJobWithConfig); RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + serviceName + "): submit job response:" + jsonResponse.toString()); return jsonResponse; }
Example 74
Project: SVQCOM-master File: NetworkServices.java View source code |
public static String PostFileUpload(String URL, HashMap<String, String> params) throws IOException { Log.i("NeworkServices", "Posting Checkins online"); entity = new MultipartEntity(); if (params != null) { Log.i("NeworkServices", "UploadFile " + params.size()); entity.addPart("task", new StringBody(params.get("task"))); entity.addPart("action", new StringBody(params.get("action"))); entity.addPart("mobileid", new StringBody(params.get("mobileid"))); entity.addPart("lat", new StringBody(params.get("lat"))); entity.addPart("lon", new StringBody(params.get("lon"))); entity.addPart("message", new StringBody(params.get("message"))); entity.addPart("firstname", new StringBody(params.get("firstname"))); entity.addPart("lastname", new StringBody(params.get("lastname"))); entity.addPart("email", new StringBody(params.get("email"))); if (!TextUtils.isEmpty(params.get("filename")) || !(params.get("filename").equals(""))) { Log.i("NeworkServices", "Posting file online"); entity.addPart("photo", new FileBody(new File(params.get("filename")))); } return MainHttpClient.SendMultiPartData(URL, entity); } return null; }
Example 75
Project: SwipeVolley-master File: MultipartRequest.java View source code |
public static MultipartEntity encodePOSTUrl(MultipartEntity mEntity, Bundle parameters) {
if (parameters != null && parameters.size() > 0) {
boolean first = true;
for (String key : parameters.keySet()) {
if (key != null) {
if (first) {
first = false;
}
String value = "";
Object object = parameters.get(key);
if (object != null) {
value = String.valueOf(object);
}
try {
mEntity.addPart(key, new StringBody(value));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return mEntity;
}
Example 76
Project: tumblr-java-master File: Post.java View source code |
/**
* @param postId
* The id of the post to be modified.
* @return HTTP status code
* @throws NoCredentialsException
* @throws ClientProtocolException
* @throws IOException
*/
public int postToTumblr(String postId) throws NoCredentialsException, ClientProtocolException, IOException {
if (email == null || password == null) {
throw new NoCredentialsException();
}
entity.addPart("post-id", new StringBody(postId));
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(POST_URL);
request.setEntity(entity);
HttpResponse response = httpclient.execute(request);
return response.getStatusLine().getStatusCode();
}
Example 77
Project: undertow-master File: ParameterCharacterEncodingTestCase.java View source code |
@Test public void testMultipartCharacterEncoding() throws IOException { TestHttpClient client = new TestHttpClient(); try { String message = "abcÄ?šž"; String charset = "UTF-8"; HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext"); MultipartEntity multipart = new MultipartEntity(); multipart.addPart("charset", new StringBody(charset, Charset.forName(charset))); multipart.addPart("message", new StringBody(message, Charset.forName(charset))); post.setEntity(multipart); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); String response = HttpClientUtils.readResponse(result); Assert.assertEquals(message, response); } finally { client.getConnectionManager().shutdown(); } }
Example 78
Project: wattzap-ce-master File: SelfLoopsAPI.java View source code |
/* * @param email -> the user email used to login on selfloops * * @param pw -> the password * * @param tcxfile -> the tcx file compressed with gzip or zip * * @param note -> a text note for the activity * * Code: 200 * * Code: 200 * * activity_id: [string], * * message: [string] * * Description: * * activity_id --> the new ride id or -1 if error occurs * * message--> a system message (text) * * error_code --> the error code (integer). * * Error Response Code: 403 (not authorized, authentication failure) */ public static int uploadActivity(String email, String passWord, String fileName, String note) throws IOException { JSONObject jsonObj = null; FileInputStream in = null; GZIPOutputStream out = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("enctype", "multipart/mixed"); in = new FileInputStream(fileName); // Create stream to compress data and write it to the to file. ByteArrayOutputStream obj = new ByteArrayOutputStream(); out = new GZIPOutputStream(obj); // Copy bytes from one stream to the other byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.close(); in.close(); ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"), fileName); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("email", new StringBody(email, ContentType.TEXT_PLAIN)).addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin).addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); switch(code) { case 200: HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); //System.out.println(content); JSONParser jsonParser = new JSONParser(); jsonObj = (JSONObject) jsonParser.parse(content); } break; case 403: throw new RuntimeException("Authentification failure " + email + " " + response.getStatusLine()); default: throw new RuntimeException("Error " + code + " " + response.getStatusLine()); } } catch (ParseException e) { e.printStackTrace(); } finally { if (response != null) { response.close(); } } int activityId = ((Long) jsonObj.get("activity_id")).intValue(); // parse error code int error = ((Long) jsonObj.get("error_code")).intValue(); if (activityId == -1) { String message = (String) jsonObj.get("message"); switch(error) { case 102: throw new RuntimeException("Empty TCX file " + fileName); case 103: throw new RuntimeException("Invalide TCX Format " + fileName); case 104: throw new RuntimeException("TCX Already Present " + fileName); case 105: throw new RuntimeException("Invalid XML " + fileName); case 106: throw new RuntimeException("invalid compression algorithm"); case 107: throw new RuntimeException("Invalid file mime types"); default: throw new RuntimeException(message + " " + error); } } return activityId; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } httpClient.close(); } }
Example 79
Project: Wilma-master File: BrowserMobHttpRequest.java View source code |
//MAIN METHOD
public BrowserMobHttpResponse execute() {
// deal with PUT/POST requests
if (method instanceof HttpEntityEnclosingRequestBase) {
HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) method;
if (!nvps.isEmpty()) {
try {
if (!multiPart) {
enclosingRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} else {
for (NameValuePair nvp : nvps) {
multipartEntity.addPart(nvp.getName(), new StringBody(nvp.getValue()));
}
enclosingRequest.setEntity(multipartEntity);
}
} catch (UnsupportedEncodingException e) {
LOG.severe("Could not find UTF-8 encoding, something is really wrong", e);
}
} else if (multipartEntity != null) {
enclosingRequest.setEntity(multipartEntity);
} else if (byteArrayEntity != null) {
enclosingRequest.setEntity(byteArrayEntity);
} else if (stringEntity != null) {
enclosingRequest.setEntity(stringEntity);
} else if (inputStreamEntity != null) {
enclosingRequest.setEntity(inputStreamEntity);
}
}
return client.execute(this);
}
Example 80
Project: wisdom-master File: MultipartBody.java View source code |
/**
* Computes the request payload.
*
* @return the payload containing the declared fields and files.
*/
public HttpEntity getEntity() {
if (hasFile) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Entry<String, Object> part : parameters.entrySet()) {
if (part.getValue() instanceof File) {
hasFile = true;
builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
} else {
builder.addPart(part.getKey(), new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
}
}
return builder.build();
} else {
try {
return new UrlEncodedFormEntity(getList(parameters), UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
Example 81
Project: 4pdaClient-plus-master File: HttpHelper.java View source code |
public String uploadFile(final String url, String filePath, Map<String, String> additionalHeaders, final ProgressState progress) throws Exception {
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
sendHeaders.put(HttpHelper.CONTENT_TYPE, "multipart/form-data;");
// add encoding cat_name for gzip if not present
if (!sendHeaders.containsKey(HttpHelper.ACCEPT_ENCODING)) {
sendHeaders.put(HttpHelper.ACCEPT_ENCODING, HttpHelper.GZIP);
}
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
if (url.contains("savepice")) {
for (Cookie cookie : getCookieStore().getCookies()) {
if (cookie.getName().equals("PHPSESSID")) {
request.addHeader("Cookie", cookie.getName() + "=" + cookie.getValue());
}
}
request.removeHeaders("User-Agent");
request.addHeader("Cache-Control", "max-age=0");
request.addHeader("Upgrade-Insecure-Reaquest", "1");
request.addHeader("Accept", "text-/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
request.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36 OPR/38.0.2220.31");
request.addHeader("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
request.addHeader("Referer", "http://savepice.ru/");
request.addHeader("Origin", "http://savepice.ru");
request.addHeader("X-Requested-With", "XMLHttpRequest");
}
}
});
}
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.setCharset(Charset.forName("windows-1251"));
File uploadFile = new File(filePath);
Log.d("save", "url: " + url + "; result: " + (url.contains("savepic") ? "file" : "FILE_UPLOAD"));
multipartEntity.addBinaryBody(url.contains("savepice") ? "file" : "FILE_UPLOAD", uploadFile, ContentType.create("image/png"), FileUtils.getFileNameFromUrl(filePath));
m_RedirectUri = null;
HttpPost httppost = new HttpPost(url);
if (additionalHeaders != null)
for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
}
final HttpEntity yourEntity = multipartEntity.build();
final long totalSize = uploadFile.length();
class ProgressiveEntity implements HttpEntity {
@Override
public void consumeContent() throws IOException {
yourEntity.consumeContent();
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
return yourEntity.getContent();
}
@Override
public Header getContentEncoding() {
return yourEntity.getContentEncoding();
}
@Override
public long getContentLength() {
return yourEntity.getContentLength();
}
@Override
public Header getContentType() {
return yourEntity.getContentType();
}
@Override
public boolean isChunked() {
return yourEntity.isChunked();
}
@Override
public boolean isRepeatable() {
return yourEntity.isRepeatable();
}
@Override
public boolean isStreaming() {
return yourEntity.isStreaming();
}
// CONSIDER put a _real_ delegator into here!
@Override
public void writeTo(OutputStream outstream) throws IOException {
class ProxyOutputStream extends FilterOutputStream {
/**
* @author Stephen Colebourne
*/
long totalSent;
public ProxyOutputStream(OutputStream proxy) {
super(proxy);
totalSent = 0;
}
public void write(int idx) throws IOException {
out.write(idx);
}
public void write(byte[] bts) throws IOException {
out.write(bts);
}
public void write(byte[] bts, int st, int end) throws IOException {
totalSent += end;
progress.update(null, (int) ((totalSent / (float) totalSize) * 100));
out.write(bts, st, end);
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
}
}
class ProgressiveOutputStream extends ProxyOutputStream {
public ProgressiveOutputStream(OutputStream proxy) {
super(proxy);
}
}
yourEntity.writeTo(new ProgressiveOutputStream(outstream));
}
}
ProgressiveEntity myEntity = new ProgressiveEntity();
httppost.setEntity(myEntity);
String res = client.execute(httppost, responseHandler);
if (res == null)
throw new NotReportException(App.getContext().getString(R.string.site_not_respond));
return res;
}
Example 82
Project: aincc-adventure-master File: HttpParam.java View source code |
/** * get MultipartEntity * * @since 1.0.0 * @param encoding * @return MultipartEntity */ public MultipartEntity getMultipartParams(String encoding) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { if (null != param && !param.isEmpty()) { Set<Entry<String, String>> hashSet = param.entrySet(); final Iterator<Entry<String, String>> it = hashSet.iterator(); while (it.hasNext()) { Map.Entry<String, String> me = (Map.Entry<String, String>) it.next(); entity.addPart(me.getKey(), new StringBody(me.getValue(), Charset.forName(encoding))); } } if (null != paramArray && !paramArray.isEmpty()) { Set<Entry<String, String[]>> hashSet = paramArray.entrySet(); final Iterator<Entry<String, String[]>> it = hashSet.iterator(); while (it.hasNext()) { Map.Entry<String, String[]> me = (Map.Entry<String, String[]>) it.next(); String[] values = me.getValue(); for (int i = 0; i < values.length; i++) { entity.addPart(me.getKey(), new StringBody(values[i], Charset.forName(encoding))); } } } if (null != fileParam && !fileParam.isEmpty()) { Set<Entry<String, File>> hashSet = fileParam.entrySet(); final Iterator<Entry<String, File>> it = hashSet.iterator(); while (it.hasNext()) { Map.Entry<String, File> me = (Map.Entry<String, File>) it.next(); entity.addPart(me.getKey(), new FileBody(me.getValue())); } } } catch (Exception e) { e.printStackTrace(); entity = null; } return entity; }
Example 83
Project: ajapaik-android-master File: ConfirmFragment.java View source code |
@Override protected Void doInBackground(Void... nothing) { try { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient httpClient = new DefaultHttpClient(params); HttpPost post = new HttpPost(String.format("https://%s/foto/%d/upload/", Constants.BACKEND_HOST, id)); MultipartEntity entity = new ProgressMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, this); Date date = new Date(); entity.addPart("user_file[]", new FileBody(new File(filePath))); entity.addPart("year", new StringBody(String.valueOf(date.getYear()))); entity.addPart("month", new StringBody(String.valueOf(date.getMonth()))); entity.addPart("day", new StringBody(String.valueOf(date.getDay()))); float sf = getActivity().getIntent().getFloatExtra(ConfirmActivity.EXTRA_SCALE_FACTOR, 1.0f); entity.addPart("scale_factor", new StringBody(String.valueOf(sf))); Log.d(TAG, "scale factor:" + sf); // lets hope its recent enough? Location loc = AjapaikApplication.loc; if (loc != null && System.currentTimeMillis() - loc.getTime() < 30000L) { entity.addPart("lat", new StringBody(String.valueOf(loc.getLatitude()))); entity.addPart("lon", new StringBody(String.valueOf(loc.getLongitude()))); } float[] orientation = AjapaikApplication.getOrientation(); if (orientation != null) { entity.addPart("yaw", new StringBody(String.valueOf(orientation[0]))); entity.addPart("pitch", new StringBody(String.valueOf(orientation[1]))); entity.addPart("roll", new StringBody(String.valueOf(orientation[2]))); Log.d(TAG, "yaw: " + orientation[0]); Log.d(TAG, "pitch: " + orientation[1]); Log.d(TAG, "roll: " + orientation[2]); } Session sess = Session.getActiveSession(); if (sess != null && sess.isOpened()) { entity.addPart("fb_access_token", new StringBody(sess.getAccessToken())); entity.addPart("fb_application_id", new StringBody(sess.getApplicationId())); } post.setEntity(entity); httpClient.execute(post); } catch (Exception e) { Log.e(TAG, "Upload failed", e); } return null; }
Example 84
Project: android-sensorium-master File: HTTPSUploader.java View source code |
private String uploadFiles(List<File> files) { String result = ""; try { if (URLUtil.isValidUrl(posturl)) { HttpClient httpclient = getNewHttpClient(); HttpPost httppost = new HttpPost(posturl); MultipartEntity mpEntity = new MultipartEntity(); // MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("username", new StringBody(username)); mpEntity.addPart("password", new StringBody(password)); for (File file : files) { Log.d(SensorRegistry.TAG, "preparing " + file.getName() + " for upload"); ContentBody cbFile = new FileBody(file, "application/json"); mpEntity.addPart(file.toString(), cbFile); } httppost.addHeader("username", username); httppost.addHeader("password", password); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); String reply; InputStream in = response.getEntity().getContent(); StringBuilder sb = new StringBuilder(); try { int chr; while ((chr = in.read()) != -1) { sb.append((char) chr); } reply = sb.toString(); } finally { in.close(); } result = response.getStatusLine().toString(); Log.d(SensorRegistry.TAG, "Http upload completed with response: " + result + " " + reply); } else { result = "URL invalid"; Log.d(SensorRegistry.TAG, "Invalid http upload url, aborting."); } } catch (IllegalArgumentException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (FileNotFoundException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (ClientProtocolException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } catch (IOException e) { result = "upload failed due to timeout"; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(SensorRegistry.TAG, sw.toString()); } return result; }
Example 85
Project: AndroidHttpTools-master File: RequestEntity.java View source code |
/**
* å¸¦æ–‡ä»¶ä¸Šä¼ çš„POST
*
* <pre>
* RequestMethod必须是{@link ConnectionHelper.RequestMethod#POST_WITH_FILE}}模�
* </pre>
*
* @param postValues
* @param files
* @param charset
*/
public RequestEntity setPostEntitiy(List<NameValuePair> postValues, String charset, Map<String, File> files) {
Charset c = null;
try {
c = Charset.forName(charset);
Charset.defaultCharset();
} catch (Exception e) {
c = null;
}
MultipartEntity entity;
HttpMultipartMode mode = HttpMultipartMode.BROWSER_COMPATIBLE;
if (c == null) {
entity = new MultipartEntity(mode);
} else {
entity = new MultipartEntity(mode, null, c);
}
postEntity = entity;
if (postValues != null) {
for (NameValuePair v : postValues) {
try {
entity.addPart(v.getName(), new StringBody(v.getValue()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
if (files != null) {
Iterator<Entry<String, File>> iterator = files.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, File> entry = iterator.next();
entity.addPart(entry.getKey(), new FileBody(entry.getValue()));
}
}
return this;
}
Example 86
Project: ankush-master File: UploadHandler.java View source code |
/** * Method that builds the multi-part form data request. * * @param urlString * the urlString to which the file needs to be uploaded * @param file * the actual file instance that needs to be uploaded * @param fileName * name of the file, just to show how to add the usual form * parameters * @param fileDescription * some description for the file, just to show how to add the * usual form parameters * @return server response as <code>String</code> */ public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) { HttpPost postRequest = new HttpPost(urlString); try { MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // The usual form parameters can be added this way multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); /* * Need to construct a FileBody with the file that needs to be * attached and specify the mime type of the file. Add the fileBody * to the request as an another part. This part will be considered * as file part and the rest of them as usual form-data parts */ FileBody fileBody = new FileBody(file, "application/octect-stream"); multiPartEntity.addPart("file", fileBody); postRequest.setEntity(multiPartEntity); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); return null; } return executeRequest(postRequest); }
Example 87
Project: buddycloud-android-master File: MediaModel.java View source code |
private void postMediaGeneral(Context context, final ModelCallback<JSONObject> callback, String imageUri, String url, boolean post) throws IOException { MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentResolver cr = context.getContentResolver(); final Uri streamUri = Uri.parse(imageUri); String streamType = cr.getType(streamUri); String fileName = streamUri.getLastPathSegment(); if (streamType == null) { streamType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FilenameUtils.getExtension(fileName)); } InputStream is = context.getContentResolver().openInputStream(streamUri); String realPath = FileUtils.getRealPathFromURI(context, streamUri); ModelCallback<JSONObject> tempCallback = null; File mediaFile = null; if (realPath == null) { File tempDir = context.getCacheDir(); final File tempFile = File.createTempFile("buddycloud-tmp-", MimeTypeMap.getSingleton().getExtensionFromMimeType(streamType), tempDir); IOUtils.copy(is, new FileOutputStream(tempFile)); tempCallback = new ModelCallback<JSONObject>() { @Override public void success(JSONObject response) { tempFile.delete(); callback.success(response); } @Override public void error(Throwable throwable) { tempFile.delete(); callback.error(throwable); } }; mediaFile = tempFile; } else { mediaFile = new File(realPath); tempCallback = callback; } reqEntity.addPart("data", new FileBody(mediaFile)); reqEntity.addPart("filename", new StringBody(fileName)); reqEntity.addPart("content-type", new StringBody(streamType)); reqEntity.addPart("title", new StringBody("Android upload")); if (post) { BuddycloudHTTPHelper.post(url, reqEntity, context, tempCallback); } else { BuddycloudHTTPHelper.put(url, reqEntity, context, tempCallback); } }
Example 88
Project: Cardinal-Plus-master File: Stats.java View source code |
public String uploadStats() {
try {
HttpPost post = new HttpPost("http://m.twizmwaz.in/uploadmatch.php");
NameValuePair id = new BasicNameValuePair("id", GameHandler.getGameHandler().getMatch().getUuid().toString().replaceAll("-", ""));
MultipartEntityBuilder fileBuilder = MultipartEntityBuilder.create().addBinaryBody("match", generateStats());
fileBuilder.addPart(id.getName(), new StringBody(id.getValue(), ContentType.TEXT_HTML));
post.setEntity(fileBuilder.build());
HttpClient client = HttpClientBuilder.create().build();
return EntityUtils.toString(client.execute(post).getEntity());
} catch (Exception e) {
Bukkit.getLogger().warning("Unable to upload statistics");
e.printStackTrace();
return null;
}
}
Example 89
Project: deccanplato-master File: FileImpl.java View source code |
/** * @return */ private Map<String, String> upload() { Map<String, String> outMap = new HashMap<>(); final String BOX_UPLOAD = "/files/content"; Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN)); MultipartEntity entity = new MultipartEntity(); FileBody filename = new FileBody(new File(args.get(FILE_NAME))); FileBody filename1 = new FileBody(new File("/home/pandiyaraja/Documents/AMIs")); StringBody parent_id = null; try { parent_id = new StringBody(args.get(FOLDER_ID)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.addPart("filename", filename); entity.addPart("parent_id", parent_id); TransportTools tools = new TransportTools(BOX_URI + BOX_UPLOAD, null, headerMap); tools.setFileEntity(entity); String responseBody = null; TransportResponse response = null; try { response = TransportMachinery.post(tools); responseBody = response.entityToString(); System.out.println("OUTPUT:" + responseBody); } catch (ClientProtocolException ce) { ce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } outMap.put(OUTPUT, responseBody); return outMap; }
Example 90
Project: Droid-Watcher-master File: FileSystemModule.java View source code |
private void getFile(String fullPath) {
File file = new File(fullPath);
if (!file.exists()) {
sendError(fullPath, "File does not exist or unavailable");
}
if (file.length() > MAX_FILE_SIZE) {
sendError(fullPath, "Maximum file size is: " + MAX_FILE_SIZE / 1024 + " kb.");
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SERVER_ADDRESS);
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("params", new StringBody(getParams()));
multipartEntity.addPart("file", new FileBody(file));
httppost.setEntity(multipartEntity);
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String data = EntityUtils.toString(entity, "UTF-8");
if (data.equals(ServerConst.ERROR)) {
sendError(fullPath, "File transfer is unsuccessful");
}
}
}
} catch (IOException e) {
Debug.exception(e);
} catch (Exception e) {
Debug.exception(e);
ACRA.getErrorReporter().handleSilentException(e);
}
}
Example 91
Project: fanfouapp-opensource-master File: NetworkHelper.java View source code |
public static MultipartEntity encodeMultipartParameters(final List<SimpleRequestParam> params) {
if (CommonHelper.isEmpty(params)) {
return null;
}
final MultipartEntity entity = new MultipartEntity();
try {
for (final SimpleRequestParam param : params) {
if (param.isFile()) {
entity.addPart(param.getName(), new FileBody(param.getFile()));
} else {
entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(HTTP.UTF_8)));
}
}
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
return entity;
}
Example 92
Project: georeport-android-master File: HttpManager.java View source code |
public static String uploadFile(String serviceEndpoint, Properties properties, String fileParam, String file) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(serviceEndpoint);
MultipartEntity entity = new MultipartEntity();
Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator();
while (i.hasNext()) {
Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next();
String key = (String) entry.getKey();
String val = (String) entry.getValue();
entity.addPart(key, new StringBody(val));
}
File upload = new File(file);
Log.i("httpman", "upload file (" + upload.getAbsolutePath() + ") size=" + upload.length());
entity.addPart(fileParam, new FileBody(upload));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
} else {
}
return response.toString();
}
Example 93
Project: gradle-ecgine-plugin-master File: EcgineDeployTask.java View source code |
private void createEbundle(HttpClient client, EcgineExtension ext, EManifest p) throws Exception {
HttpPost post = new HttpPost(ext.getUploadBundleUrl());
post.addHeader("apikey", ext.getApiKey());
post.removeHeaders("content-type");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = p.getJar();
if (!file.exists()) {
throw new GradleException("Run build before deploy");
}
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName());
JSONObject json = new JSONObject();
json.put("multiple", false);
builder.addPart("info", new StringBody(json.toString(), ContentType.APPLICATION_JSON));
post.setEntity(builder.build());
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
Example 94
Project: IPCPlayer-master File: QHttpClient.java View source code |
/** * Postæ–¹æ³•ä¼ é€?文件和消æ?¯ * * @param url 连接的URL * @param queryString 请求å?‚数串 * @param files ä¸Šä¼ çš„æ–‡ä»¶åˆ—è¡¨ * @return æœ?务器返回的信æ?¯ * @throws Exception */ public String httpPostWithFile(String url, String queryString, List<NameValuePair> files) throws Exception { String responseData = null; URI tmpUri = new URI(url); URI uri = URIUtils.createURI(tmpUri.getScheme(), tmpUri.getHost(), tmpUri.getPort(), tmpUri.getPath(), queryString, null); LogUtil.i(TAG, "QHttpClient httpPostWithFile [1] uri = " + uri.toURL()); MultipartEntity mpEntity = new MultipartEntity(); HttpPost httpPost = new HttpPost(uri); StringBody stringBody; FileBody fileBody; File targetFile; String filePath; FormBodyPart fbp; List<NameValuePair> queryParamList = QStrOperate.getQueryParamsList(queryString); for (NameValuePair queryParam : queryParamList) { stringBody = new StringBody(queryParam.getValue(), Charset.forName("UTF-8")); fbp = new FormBodyPart(queryParam.getName(), stringBody); mpEntity.addPart(fbp); // Log.i(TAG, "------- "+queryParam.getName()+" = "+queryParam.getValue()); } for (NameValuePair param : files) { filePath = param.getValue(); targetFile = new File(filePath); fileBody = new FileBody(targetFile, "application/octet-stream"); fbp = new FormBodyPart(param.getName(), fileBody); mpEntity.addPart(fbp); } // Log.i(TAG, "---------- Entity Content Type = "+mpEntity.getContentType()); httpPost.setEntity(mpEntity); try { HttpResponse response = httpClient.execute(httpPost); LogUtil.i(TAG, "QHttpClient httpPostWithFile [2] StatusLine = " + response.getStatusLine()); responseData = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { httpPost.abort(); } LogUtil.i(TAG, "QHttpClient httpPostWithFile [3] responseData = " + responseData); return responseData; }
Example 95
Project: jackan-master File: ExperimentalCkanClient.java View source code |
/** * Uploads a file using file storage api, which I think is deprecated. As of * Aug 2015, coesn't work neither with demo.ckan.org nor dati.trentino * * Adapted from * https://github.com/Ontodia/openrefine-ckan-storage-extension/blob/c99de78fd605c4754197668c9396cffd1f9a0267/src/org/deri/orefine/ckan/StorageApiProxy.java#L34 */ public String uploadFile(String fileContent, String fileLabel) { HttpResponse formFields = null; try { String filekey = null; HttpClient client = new DefaultHttpClient(); // get the form fields required from ckan storage // notice if you put '3/' it gives not found :-/ String formUrl = getCatalogUrl() + "/api/storage/auth/form/file/" + fileLabel; HttpGet getFormFields = new HttpGet(formUrl); getFormFields.setHeader("Authorization", getCkanToken()); formFields = client.execute(getFormFields); HttpEntity entity = formFields.getEntity(); if (entity != null) { ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); //now parse JSON //JSONObject obj = new JSONObject(os.toString()); JsonNode obj = new ObjectMapper().readTree(os.toString()); //post the file now String uploadFileUrl = getCatalogUrl() + obj.get("action").asText(); HttpPost postFile = new HttpPost(uploadFileUrl); postFile.setHeader("Authorization", getCkanToken()); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT); //JSONArray fields = obj.getJSONArray("fields"); Iterator<JsonNode> fields = obj.get("fields").elements(); while (fields.hasNext()) { JsonNode fieldObj = fields.next(); //JSONObject fieldObj = fields.getJSONObject(i); String fieldName = fieldObj.get("name").asText(); String fieldValue = fieldObj.get("value").asText(); if (fieldName.equals("key")) { filekey = fieldValue; } mpEntity.addPart(fieldName, new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8"))); } // assure that we got the file key if (filekey == null) { throw new RuntimeException("failed to get the file key from CKAN storage form API. the response from " + formUrl + " was: " + os.toString()); } //the file should be the last part //hack... StringBody didn't work with large files mpEntity.addPart("file", new ByteArrayBody(fileContent.getBytes(Charset.forName("UTF-8")), "multipart/form-data", fileLabel)); postFile.setEntity(mpEntity); HttpResponse fileUploadResponse = client.execute(postFile); //check if the response status code was in the 200 range if (fileUploadResponse.getStatusLine().getStatusCode() < 200 || fileUploadResponse.getStatusLine().getStatusCode() >= 300) { throw new RuntimeException("failed to add the file to CKAN storage. response status line from " + uploadFileUrl + " was: " + fileUploadResponse.getStatusLine()); } return getCatalogUrl() + "/storage/f/" + filekey; //return CKAN_STORAGE_FILES_BASE_URI + filekey; } throw new RuntimeException("failed to get form details from CKAN storage. response line was: " + formFields.getStatusLine()); } catch (IOException ioe) { throw new RuntimeException("failed to upload file to CKAN Storage ", ioe); } }
Example 96
Project: jaxygen-master File: JaxygenClient.java View source code |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodUrl = urlBase + "/" + method.getName(); HttpPost post = new HttpPost(methodUrl); MultipartEntity mp = new MultipartEntity(); if (session.cookies != null) { StringBuilder cookiesStr = new StringBuilder(256); for (String cookie : session.cookies) { cookiesStr.append(cookie); cookiesStr.append(";"); } if (cookiesStr.length() > 0) { LOGGER.log(Level.INFO, "cookies: ", cookiesStr); post.setHeader("Cookie", cookiesStr.substring(0)); } } if (args != null) { for (Object o : args) { IOProxy p = new IOProxy(); String json = gson.toJson(o); //mp.addPart(o.getClass().getName(), new InputStreamBody(p, "text/json", o.getClass().getName())); mp.addPart(o.getClass().getName(), new InputStreamBody(new ByteArrayInputStream(json.getBytes(Charset.forName("UTF-8"))), "text/json", o.getClass().getName())); } } mp.addPart(new FormBodyPart("inputType", new StringBody(JsonMultipartRequestConverter.NAME))); mp.addPart(new FormBodyPart("outputType", new StringBody(SJOResponseConverter.NAME))); post.setEntity(mp); HttpResponse response = new DefaultHttpClient().execute(post); final HttpEntity e = response.getEntity(); Header[] hCookies = response.getHeaders("Set-Cookie"); if (hCookies != null) { for (Header h : hCookies) { session.cookies.add(h.getValue()); } } ObjectInputStream osi = null; final StringBuffer sb = new StringBuffer(256); try { InputStream inputProxy = new InputStream() { @Override public int read() throws IOException { int b = e.getContent().read(); if (sb.length() < 1024) { sb.append((char) b); } return b; } }; Throwable appException = null; try { osi = new ObjectInputStream(inputProxy); Response wrappedResponse = (Response) osi.readObject(); if (wrappedResponse instanceof ExceptionResponse) { ExceptionResponse exr = (ExceptionResponse) wrappedResponse; Class<Throwable> exClass = (Class<Throwable>) getClass().getClassLoader().loadClass(exr.getExceptionData().getExceptionClass()); appException = exClass.newInstance(); } if (appException == null) { if (SecurityProfile.class.equals(method.getReturnType())) { return convertDtoToSecurityProfile((SecurityProfileDTO) wrappedResponse.getDto().getResponseObject()); } else { return wrappedResponse.getDto().getResponseObject(); } } } catch (Throwable ex) { throw new InvocationTargetException(ex, "Unexpected server response: " + sb.toString()); } if (appException != null) { throw appException; } } finally { if (osi != null) { osi.close(); } } return null; }
Example 97
Project: kanqiu_letv-master File: QHttpClient.java View source code |
/** * Postæ–¹æ³•ä¼ é€?文件和消æ?¯ * * @param url 连接的URL * @param queryString 请求å?‚数串 * @param files ä¸Šä¼ çš„æ–‡ä»¶åˆ—è¡¨ * @return æœ?务器返回的信æ?¯ * @throws Exception */ public String httpPostWithFile(String url, String queryString, List<NameValuePair> files) throws Exception { String responseData = null; URI tmpUri = new URI(url); URI uri = URIUtils.createURI(tmpUri.getScheme(), tmpUri.getHost(), tmpUri.getPort(), tmpUri.getPath(), queryString, null); Log.i(TAG, "QHttpClient httpPostWithFile [1] uri = " + uri.toURL()); MultipartEntity mpEntity = new MultipartEntity(); HttpPost httpPost = new HttpPost(uri); StringBody stringBody; FileBody fileBody; File targetFile; String filePath; FormBodyPart fbp; List<NameValuePair> queryParamList = QStrOperate.getQueryParamsList(queryString); for (NameValuePair queryParam : queryParamList) { stringBody = new StringBody(queryParam.getValue(), Charset.forName("UTF-8")); fbp = new FormBodyPart(queryParam.getName(), stringBody); mpEntity.addPart(fbp); // Log.i(TAG, "------- "+queryParam.getName()+" = "+queryParam.getValue()); } for (NameValuePair param : files) { filePath = param.getValue(); targetFile = new File(filePath); fileBody = new FileBody(targetFile, "application/octet-stream"); fbp = new FormBodyPart(param.getName(), fileBody); mpEntity.addPart(fbp); } // Log.i(TAG, "---------- Entity Content Type = "+mpEntity.getContentType()); httpPost.setEntity(mpEntity); try { HttpResponse response = httpClient.execute(httpPost); Log.i(TAG, "QHttpClient httpPostWithFile [2] StatusLine = " + response.getStatusLine()); responseData = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { httpPost.abort(); } Log.i(TAG, "QHttpClient httpPostWithFile [3] responseData = " + responseData); return responseData; }
Example 98
Project: kornan-android-master File: MultiPartStack.java View source code |
/** * If Request is MultiPartRequest type, then set MultipartEntity in the * httpRequest object. * * @param httpRequest * @param request * @throws AuthFailureError */ private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { // Return if Request is not MultiPartRequest if (!(request instanceof MultiPartRequest)) { return; } MultipartEntity builder = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // MultipartEntityBuilder builder = MultipartEntityBuilder.create(); /* example for setting a HttpMultipartMode */ // builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Iterate the fileUploads // Map<String, File> fileUpload = ((MultiPartRequest) request) // .getFileUploads(); // for (Map.Entry<String, File> entry : fileUpload.entrySet()) { // builder.addPart(((String) entry.getKey()), new FileBody( // (File) entry.getValue())); // } ArrayList<Map<String, File>> fileUpload = ((MultiPartRequest) request).getFileUploads(); for (int i = 0; i < fileUpload.size(); i++) { Map<String, File> fileMap = fileUpload.get(i); for (Map.Entry<String, File> entry : fileMap.entrySet()) { builder.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue())); } } // ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, // HTTP.UTF_8); // Iterate the stringUploads Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads(); for (Map.Entry<String, String> entry : stringUpload.entrySet()) { try { // builder.addPart(((String) entry.getKey()), // new StringBody((String) entry.getValue(), contentType)); builder.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName(HTTP.UTF_8))); } catch (Exception e) { e.printStackTrace(); } } httpRequest.setEntity(builder); }
Example 99
Project: Lima1-master File: HttpClientTransport.java View source code |
@SuppressWarnings("unchecked")
@Override
public JSONObject request(String uri, RequestType type, Object data, String contentType) throws NetTransportException {
int code = 500;
try {
Log.i(TAG, "Request: " + uri + ", " + type);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
schemeRegistry.register(new Scheme("https", sf, 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
httpClient.setParams(params);
if (proxyHost != null && proxyPort > 0) {
params.setParameter(ConnRouteParams.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient nHttpClient = new DefaultHttpClient(cm, params);
HttpUriRequest request = new HttpGet(url + uri);
if (null != data && type != RequestType.Get) {
HttpPost post = new HttpPost(url + uri);
if (data instanceof Map) {
Map<String, Object> map = (Map<String, Object>) data;
boolean multipart = false;
for (Object value : // Check
((Map) data).values()) {
if (// At least one is file
value instanceof File) {
multipart = true;
break;
}
}
//
if (multipart) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (String key : map.keySet()) {
Object value = map.get(key);
if (// File entity
value instanceof File) {
entity.addPart(key, new FileBody((File) value, "application/octet-stream"));
} else {
entity.addPart(key, new StringBody(value.toString()));
}
}
post.setEntity(entity);
//
} else {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (String key : map.keySet()) {
pairs.add(new BasicNameValuePair(key, map.get(key).toString()));
}
post.setEntity(new UrlEncodedFormEntity(pairs));
}
}
if (data instanceof JSONObject) {
JSONObject json = (JSONObject) data;
StringEntity entity = new StringEntity(json.toString(), "utf-8");
if (null != contentType) {
entity.setContentType(contentType);
}
post.setEntity(entity);
}
request = post;
}
HttpResponse response = nHttpClient.execute(request);
code = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (null != entity) {
JSONObject result = new JSONObject(readString(entity));
if (200 == code) {
return result;
}
Log.i(TAG, "JSON: " + result);
throw new NetTransportException(code, result.optString("message", result.optString("error_description", "No error message")), null);
}
throw new NetTransportException(code, "No response", null);
} catch (NetTransportException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
throw new NetTransportException(code, e.getMessage(), e);
}
}
Example 100
Project: mechanize-master File: RequestBuilder.java View source code |
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; }
Example 101
Project: MoapGpsTracker-master File: OSMHelper.java View source code |
public void run() { try { HttpPost request = new HttpPost(gpsTraceUrl); consumer.sign(request); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody gpxBody = new FileBody(chosenFile); entity.addPart("file", gpxBody); if (description == null || description.length() <= 0) { description = "GPSLogger for Android"; } entity.addPart("description", new StringBody(description)); entity.addPart("tags", new StringBody(tags)); entity.addPart("visibility", new StringBody(visibility)); request.setEntity(entity); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); Utilities.LogDebug("OSM Upload - " + String.valueOf(statusCode)); helper.OnComplete(); } catch (Exception e) { helper.OnFailure(); Utilities.LogError("OsmUploadHelper.run", e); } }