List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text, Charset charset) throws UnsupportedEncodingException
From source file:it.restrung.rest.client.DefaultRestClientImpl.java
/** * Private helper to setup a multipart request body *///www .java 2 s. c om private static void setupMultipartBodyWithFile(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, APIPostParams apiPostParams, String body, File file) throws UnsupportedEncodingException { //MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); CountingMultipartEntity mpEntity = new CountingMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"), file != null ? body.length() + file.length() : body.length(), apiPostParams); mpEntity.addPart("body", new StringBody(body, Charset.forName("UTF-8"))); if (file != null) { FileBody uploadFilePart = new FileBody(file, "application/octet-stream"); mpEntity.addPart("file", uploadFilePart); } httpEntityEnclosingRequestBase.setHeader(mpEntity.getContentType()); httpEntityEnclosingRequestBase.setEntity(mpEntity); }
From source file:com.liferay.sync.engine.session.Session.java
private StringBody _getStringBody(Object value) { return new StringBody(String.valueOf(value), ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), Charset.forName("UTF-8"))); }
From source file:de.geomobile.joined.api.service.JOWebService.java
/** * Update users current location//ww w . j ava2 s .co m * * @param userId * The users id. * * @param secureToken * The users secureToken. * @param latitude * @param longitude * @throws JOFriendFinderUnexpectedException * @throws JOFriendFinderServerException * @throws JOFriendFinderHTTPException */ public void updateUser(String userId, String secureToken, double latitude, double longitude) throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException { try { HttpClient httpClient = getNewHttpClient(); HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId); httpput.addHeader(getAuthenticationHeader(userId, secureToken)); MultipartEntity entity = new MultipartEntity(); entity.addPart(JOConfig.LATITUDE, new StringBody(String.valueOf(latitude), Charset.forName(JOConfig.UTF_8))); entity.addPart(JOConfig.LONGITUDE, new StringBody(String.valueOf(longitude), Charset.forName(JOConfig.UTF_8))); httpput.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpput); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new JOFriendFinderServerException(); } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { throw new JOFriendFinderUnexpectedException( "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode()); } } catch (UnsupportedEncodingException e) { throw new JOFriendFinderUnexpectedException(e); } catch (ClientProtocolException e) { throw new JOFriendFinderHTTPException(e); } catch (IOException e) { throw new JOFriendFinderHTTPException(e); } }
From source file:immf.ImodeNetClient.java
/** * imode.net????// w w w. j a v a 2 s . com * * @param mail * @return * @throws IOException */ public synchronized void sendMail(SenderMail mail, boolean forcePlaintext) throws IOException, LoginException { if (this.logined == null) { log.warn("i.net????????"); this.logined = Boolean.FALSE; throw new LoginException("imode.net nologin"); } if (this.logined != null && this.logined == Boolean.FALSE) { try { this.login(); } catch (LoginException e) { throw new IOException("Could not login to imode.net"); } } List<String> inlineFileIdList = new LinkedList<String>(); List<String> attachmentFileIdList = new LinkedList<String>(); if (!forcePlaintext) { // html????? for (SenderAttachment file : mail.getInlineFile()) { String docomoFileId = this.sendAttachFile(inlineFileIdList, true, file.getContentTypeWithoutParameter(), file.getFilename(), file.getData()); file.setDocomoFileId(docomoFileId); } } List<SenderAttachment> attachFiles = mail.getAttachmentFile(); for (SenderAttachment file : attachFiles) { // ? this.sendAttachFile(attachmentFileIdList, false, file.getContentTypeWithoutParameter(), file.getFilename(), file.getData()); } // html?? boolean htmlMail = false; String body = null; if (forcePlaintext) { htmlMail = false; body = mail.getPlainBody(); } else { body = mail.getHtmlBody(true); if (body == null) { htmlMail = false; body = mail.getPlainBody(); } else { htmlMail = true; } } // html??????cid? if (htmlMail) { // (???? <img src="40_... ??) body = HtmlConvert.replaceAllCaseInsenstive(body, "<img src=\"cid:[^>]*>", ""); } log.info("Html " + htmlMail); log.info("body " + body); MultipartEntity multi = new MultipartEntity(); try { multi.addPart("folder.id", new StringBody("0", Charset.forName("UTF-8"))); String mailType = null; if (htmlMail) { mailType = "1"; } else { mailType = "0"; } multi.addPart("folder.mail.type", new StringBody(mailType, Charset.forName("UTF-8"))); // ? int recipient = 0; for (InternetAddress ia : mail.getTo()) { multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr", new StringBody(ia.getAddress(), Charset.forName("UTF-8"))); multi.addPart("folder.mail.addrinfo(" + recipient + ").type", new StringBody("1", Charset.forName("UTF-8"))); recipient++; } for (InternetAddress ia : mail.getCc()) { multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr", new StringBody(ia.getAddress(), Charset.forName("UTF-8"))); multi.addPart("folder.mail.addrinfo(" + recipient + ").type", new StringBody("2", Charset.forName("UTF-8"))); recipient++; } for (InternetAddress ia : mail.getBcc()) { multi.addPart("folder.mail.addrinfo(" + recipient + ").mladdr", new StringBody(ia.getAddress(), Charset.forName("UTF-8"))); multi.addPart("folder.mail.addrinfo(" + recipient + ").type", new StringBody("3", Charset.forName("UTF-8"))); recipient++; } if (recipient > 5) { throw new IOException("Too Much Recipient"); } // ?? multi.addPart("folder.mail.subject", new StringBody(Util.reverseReplaceUnicodeMapping(mail.getSubject()), Charset.forName("UTF-8"))); // body = Util.reverseReplaceUnicodeMapping(body); // imode.net?? ?10000Bytes? if (body.getBytes().length > 10000) { // ?byte???????????byte?? log.warn("????????10000byte"); throw new IOException("Too Big Message Body. Max 10000 byte."); } multi.addPart("folder.mail.data", new StringBody(body, Charset.forName("UTF-8"))); if (!attachmentFileIdList.isEmpty()) { // for (int i = 0; i < attachmentFileIdList.size(); i++) { multi.addPart("folder.tmpfile(" + i + ").file(0).id", new StringBody(attachmentFileIdList.get(i), Charset.forName("UTF-8"))); } } // ?????? multi.addPart("iemoji(0).id", new StringBody(Character.toString((char) 0xe709), Charset.forName("UTF-8"))); // e709 = UTF-8?ee89c9? multi.addPart("iemoji(1).id", new StringBody(Character.toString((char) 0xe6f0), Charset.forName("UTF-8"))); // e6f0 = UTF-8?ee9bb0? multi.addPart("reqtype", new StringBody("0", Charset.forName("UTF-8"))); HttpPost post = new HttpPost(SendMailUrl); try { addDumyHeader(post); post.setEntity(multi); HttpResponse res = this.executeHttp(post); if (!isJson(res)) { log.warn("?JSON??????"); if (res != null) { // JSON????????????????? log.debug(toStringBody(res)); this.logined = Boolean.FALSE; throw new LoginException("Bad response. no json format."); } else { throw new IOException("imode.net not responding. Try later."); } } JSONObject json = JSONObject.fromObject(toStringBody(res)); String result = json.getJSONObject("common").getString("result"); if (result.equals("PW1409")) { // ???? this.logined = Boolean.FALSE; throw new IOException("PW1409 - session terminated because of your bad mail."); } else if (result.equals("PW1430")) { // ??? throw new IOException("PW1430 - User Unknown."); } else if (result.equals("PW1436")) { // ????? JSONArray jsonaddrs = json.getJSONObject("data").getJSONArray("seaddr"); String addrs = ""; for (int i = 0; i < jsonaddrs.size(); i++) { if (i > 0) { addrs += ", "; } addrs += jsonaddrs.getString(i); } throw new IOException("PW1436 - User Unknown.: " + addrs); } else if (!result.equals("PW1000")) { log.debug(json.toString(2)); throw new IOException("Bad response " + result); } } finally { post.abort(); log.info("??"); } } catch (UnsupportedEncodingException e) { log.fatal(e); } }
From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(Long... values) { mResults = new HashMap<String, String>(); String postResponse;//from w w w. j a v a 2s . com String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + InstanceColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. HttpContext localContext = MIntel.getInstance().getHttpContext(); HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) { return mResults; } publishProgress(c.getPosition() + 1, c.getCount()); String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } ContentValues cv = new ContentValues(); URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:com.mpower.daktar.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(final Long... values) { mResults = new HashMap<String, String>(); String postResponse;//w ww . jav a2s .c o m String selection = BaseColumns._ID + "=?"; final String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + BaseColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. final HttpContext localContext = MIntel.getInstance().getHttpContext(); final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); final Map<URI, URI> uriRemap = new HashMap<URI, URI>(); final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) return mResults; publishProgress(c.getPosition() + 1, c.getCount()); final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String id = c.getString(c.getColumnIndex(BaseColumns._ID)); final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { final SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } final ContentValues cv = new ContentValues(); URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { final Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); final URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (final ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file final File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory final File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files final List<File> files = new ArrayList<File>(); for (final File f : allFiles) { final String fileName = f.getName(); final int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); final MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post final MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { final File f = files.get(j); final String fileName = f.getName(); final int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { final StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (final Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); final int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } final HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (final IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java
private void addFormData() throws cfmRunTimeException { Map<String, String> formData = httpData.getFormData(); Iterator<String> keys = formData.keySet().iterator(); String nextKey;/* w w w . j ava2s. c o m*/ if (message.getMethod().equalsIgnoreCase("POST")) { if (isMultipart || httpData.getFiles().size() > 0) { if (multipartEntityBuilder == null) multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset); while (keys.hasNext()) { nextKey = keys.next(); multipartEntityBuilder.addPart(nextKey, new StringBody(formData.get(nextKey), ContentType.TEXT_PLAIN)); } } else { Header contentType = message.getFirstHeader("Content-type"); if (contentType == null) { // otherwise it's been set manually so don't override it message.setHeader("Content-type", "application/x-www-form-urlencoded"); } StringBuilder paramStr = new StringBuilder(); while (keys.hasNext()) { nextKey = keys.next(); paramStr.append(nextKey); paramStr.append('='); paramStr.append(formData.get(nextKey)); paramStr.append('&'); } if (paramStr.length() > 0) { paramStr.deleteCharAt(paramStr.length() - 1); // remove last & ((HttpPost) message).setEntity(new StringEntity(paramStr.toString(), this.charset)); } } } }
From source file:de.geomobile.joined.api.service.JOWebService.java
/** * Activate or deactivate user//from ww w. j av a 2s.co m * * @param userId * The users id. * * @param secureToken * The users secureToken. * @param active * active or deactive * @throws JOFriendFinderUnexpectedException * @throws JOFriendFinderServerException * @throws JOFriendFinderHTTPException */ public void activateUser(String userId, String secureToken, boolean active) throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException { try { HttpClient httpClient = getNewHttpClient(); HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId); httpput.addHeader(getAuthenticationHeader(userId, secureToken)); MultipartEntity entity = new MultipartEntity(); entity.addPart(JOConfig.IS_ACTIVE, new StringBody(String.valueOf(active), Charset.forName(JOConfig.UTF_8))); httpput.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpput); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new JOFriendFinderServerException(); } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { throw new JOFriendFinderUnexpectedException( "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode()); } } catch (UnsupportedEncodingException e) { throw new JOFriendFinderUnexpectedException(e); } catch (ClientProtocolException e) { throw new JOFriendFinderHTTPException(e); } catch (IOException e) { throw new JOFriendFinderHTTPException(e); } }
From source file:de.geomobile.joined.api.service.JOWebService.java
/** * User logout.//from w w w . j av a2 s .com * * @param userId * The users id. * * @param secureToken * The users secureToken. * @throws JOFriendFinderUnexpectedException * @throws JOFriendFinderServerException * @throws JOFriendFinderHTTPException */ public void logoutUser(String userId, String secureToken) throws JOFriendFinderUnexpectedException, JOFriendFinderServerException, JOFriendFinderHTTPException { try { HttpClient httpClient = getNewHttpClient(); HttpPut httpput = new HttpPut(getJoinedServerUrl() + JOConfig.FF_FRIENDS + "/" + userId); httpput.addHeader(getAuthenticationHeader(userId, secureToken)); MultipartEntity entity = new MultipartEntity(); entity.addPart(JOConfig.REGISTRATION_ID, new StringBody("", Charset.forName(JOConfig.UTF_8))); entity.addPart(JOConfig.IS_ACTIVE, new StringBody(String.valueOf(false), Charset.forName(JOConfig.UTF_8))); httpput.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpput); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new JOFriendFinderServerException(); } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { throw new JOFriendFinderUnexpectedException( "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode()); } } catch (UnsupportedEncodingException e) { throw new JOFriendFinderUnexpectedException(e); } catch (ClientProtocolException e) { throw new JOFriendFinderHTTPException(e); } catch (IOException e) { throw new JOFriendFinderHTTPException(e); } }