Advertisement
Guest User

Untitled

a guest
Jan 15th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.96 KB | None | 0 0
  1. public class FormUploader2 extends AsyncTask<String,Void,String> {
  2.  
  3. String username = omitted;
  4. String password = omitted;
  5. String crlf = "\r\n";
  6. String twoHyphens = "--";
  7. String boundary = "*****";
  8. String formName = "CR Debitage Form v1_2019-01-14_14-42-01.xml";
  9. File file;
  10.  
  11. protected String doInBackground(String...p){
  12. String result = " ";
  13.  
  14. //Load file
  15. file = new File(Environment.getExternalStorageDirectory(), formName);
  16.  
  17. if(file.isFile()) {
  18. try {
  19. final URL url = new URL("http://omitted/ODKAggregate/submission");
  20. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  21.  
  22. // Check server response
  23. String debug = "";
  24. int status = conn.getResponseCode();
  25.  
  26. if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
  27. //This is expected as we haven't supplied any login credentials. Unfortunately
  28. //Android's built in digest authentication support is shit, so we have to build it based
  29. //on this failed response
  30. HttpURLConnection connection = tryDigestAuthentication(conn, username, password);
  31.  
  32. if(connection == null){
  33. throw new IOException("Authentication Error- Digest processing failed");
  34. } else {
  35. conn = connection;
  36. upload(conn);
  37. }
  38.  
  39. } else {
  40. throw new IOException("Authentication Error: " + status);
  41. }
  42. } catch (IOException i) {
  43. i.printStackTrace();
  44. Log.e("IO Exception - ", i.toString());
  45. }
  46. } else {
  47. result = "No File detected";
  48. }
  49.  
  50. return result;
  51. }
  52.  
  53. public void upload(HttpURLConnection conn) {
  54. try {
  55. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
  56. String formattedDate = sdf.format(new Date());
  57.  
  58. conn.setDoOutput(true);
  59. conn.setRequestProperty("Content-Type", "multipart/form-data");
  60. conn.setRequestProperty("X-OpenRosa-Version", "1.0");
  61. conn.setRequestProperty("Date", formattedDate);
  62. conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
  63. conn.setRequestProperty("Connection", "Keep-Alive");
  64. conn.setRequestProperty("Cache-Control", "no-cache");
  65. conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
  66.  
  67. OutputStream outputStream = conn.getOutputStream();
  68. PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8").newEncoder()), true);
  69.  
  70. writer.append(twoHyphens + boundary + crlf);
  71. writer.append("Content-Disposition: form-data; name=\"xml_submission_file\"; filename=\"" + formName + "\"" + crlf);
  72. writer.append("Content-Type: text/xml;" + crlf + crlf);
  73. writer.flush();
  74.  
  75. FileInputStream inputStream = new FileInputStream(file);
  76. byte[] buffer = new byte[4096];
  77. int bytesRead = -1;
  78. while ((bytesRead = inputStream.read(buffer)) != -1) {
  79. outputStream.write(buffer, 0, bytesRead);
  80. }
  81.  
  82. outputStream.flush();
  83. inputStream.close();
  84. writer.append(crlf);
  85. writer.flush();
  86. writer.append(crlf);
  87. writer.flush();
  88. writer.append(twoHyphens + boundary + twoHyphens);
  89. writer.append(crlf);
  90.  
  91. String post = writer.toString();
  92. writer.close();
  93.  
  94. // Check server response
  95. String debug = "";
  96. int status = conn.getResponseCode();
  97.  
  98. if (status == HttpURLConnection.HTTP_OK) {
  99. BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  100. String line = null;
  101. while ((line = reader.readLine()) != null) {
  102. debug = debug + line;
  103. }
  104.  
  105. reader.close();
  106. conn.disconnect();
  107. } else {
  108. throw new IOException("Server returned non-OK status: " + status + " " + post);
  109. }
  110. } catch (MalformedURLException m) {
  111. m.printStackTrace();
  112. Log.e("URL Exception - ", m.toString());
  113. } catch (IOException i) {
  114. i.printStackTrace();
  115. Log.e("IO Exception - ", i.toString());
  116. }
  117. }
  118.  
  119. public static HttpURLConnection tryDigestAuthentication(HttpURLConnection input, String username, String password) {
  120. String auth = input.getHeaderField("WWW-Authenticate");
  121. if(auth == null || !auth.startsWith("Digest ")){
  122. return null;
  123. }
  124.  
  125. final HashMap<String, String> authFields = splitAuthFields(auth.substring(7));
  126.  
  127. MessageDigest md5 = null;
  128. try{
  129. md5 = MessageDigest.getInstance("MD5");
  130. } catch(NoSuchAlgorithmException e){
  131. return null;
  132. }
  133.  
  134. String j = ":";
  135. String HA1 = null;
  136.  
  137. try{
  138. md5.reset();
  139. String ha1str = username + j + authFields.get("realm") + j + password;
  140. md5.update(ha1str.getBytes("ISO-8859-1"));
  141. byte[] ha1bytes = md5.digest();
  142. HA1 = bytesToHexString(ha1bytes);
  143. } catch(UnsupportedEncodingException e){
  144. return null;
  145. }
  146.  
  147. String HA2 = null;
  148. try{
  149. md5.reset();
  150. String ha2str = (input.getRequestMethod() + j + input.getURL().getPath());
  151. md5.update(ha2str.getBytes("ISO-8859-1"));
  152. HA2 = bytesToHexString(md5.digest());
  153. } catch(UnsupportedEncodingException e){
  154. return null;
  155. }
  156.  
  157. String HA3 = null;
  158. String cnoice = generateCNonce();
  159. try{
  160. md5.reset();
  161. String ha3str = (HA1 + j + authFields.get("nonce") + j + "1" + cnoice + "auth" + HA2);
  162. md5.update(ha3str.getBytes("ISO-8859-1"));
  163. HA3 = bytesToHexString(md5.digest());
  164. } catch(UnsupportedEncodingException e){
  165. return null;
  166. }
  167.  
  168. StringBuilder sb = new StringBuilder(128);
  169. sb.append("Digest ");
  170. sb.append("username").append("=\"").append(username).append("\", ");
  171. sb.append("realm").append("=\"").append(authFields.get("realm")).append("\", ");
  172. sb.append("nonce").append("=\"").append(authFields.get("nonce")).append("\", ");
  173. sb.append("uri").append("=\"").append(input.getURL().getPath()).append("\", ");
  174. sb.append("response").append("=\"").append(HA3).append("\", ");
  175. sb.append("qop").append('=').append("auth").append(", ");
  176. sb.append("nc").append("=\"").append("1").append("\", ");
  177. sb.append("cnonce").append("=\"").append(cnoice).append("\"");
  178.  
  179. //sb.append("algorithm").append("=\"").append(authFields.get("algorithm")).append("\"");
  180.  
  181. try{
  182. final HttpURLConnection result = (HttpURLConnection)input.getURL().openConnection();
  183. result.addRequestProperty("Authorization", sb.toString());
  184. return result;
  185. }
  186. catch(IOException e){
  187. return null;
  188. }
  189. }
  190.  
  191. private static HashMap<String, String> splitAuthFields(String authString)
  192. {
  193. final HashMap<String, String> fields = Maps.newHashMap();
  194. final CharMatcher trimmer = CharMatcher.anyOf("\"\t ");
  195. final Splitter commas = Splitter.on(',').trimResults().omitEmptyStrings();
  196. final Splitter equals = Splitter.on('=').trimResults(trimmer).limit(2);
  197. String[] valuePair;
  198. for(String keyPair : commas.split(authString)){
  199. valuePair = Iterables.toArray(equals.split(keyPair), String.class);
  200. fields.put(valuePair[0], valuePair[1]);
  201. }
  202. return fields;
  203. }
  204.  
  205. private static final String HEX_LOOKUP = "0123456789abcdef";
  206. private static String bytesToHexString(byte[] bytes)
  207. {
  208. StringBuilder sb = new StringBuilder(bytes.length * 2);
  209. for(int i = 0; i < bytes.length; i++){
  210. sb.append(HEX_LOOKUP.charAt((bytes[i] & 0xF0) >> 4));
  211. sb.append(HEX_LOOKUP.charAt((bytes[i] & 0x0F) >> 0));
  212. }
  213. return sb.toString();
  214. }
  215.  
  216. public static class AuthenticationException extends IOException
  217. {
  218. private static final long serialVersionUID = 1L;
  219. public AuthenticationException()
  220. {
  221. super("Problems authenticating");
  222. }
  223. }
  224.  
  225. private static String generateCNonce() {
  226. String s = "";
  227. for (int i = 0; i < 8; i++)
  228.  
  229. s += Integer.toHexString(new Random().nextInt(16));
  230. return s;
  231. }
  232.  
  233. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement