Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FormUploader2 extends AsyncTask<String,Void,String> {
- String username = omitted;
- String password = omitted;
- String crlf = "\r\n";
- String twoHyphens = "--";
- String boundary = "*****";
- String formName = "CR Debitage Form v1_2019-01-14_14-42-01.xml";
- File file;
- protected String doInBackground(String...p){
- String result = " ";
- //Load file
- file = new File(Environment.getExternalStorageDirectory(), formName);
- if(file.isFile()) {
- try {
- final URL url = new URL("http://omitted/ODKAggregate/submission");
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- // Check server response
- String debug = "";
- int status = conn.getResponseCode();
- if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
- //This is expected as we haven't supplied any login credentials. Unfortunately
- //Android's built in digest authentication support is shit, so we have to build it based
- //on this failed response
- HttpURLConnection connection = tryDigestAuthentication(conn, username, password);
- if(connection == null){
- throw new IOException("Authentication Error- Digest processing failed");
- } else {
- conn = connection;
- upload(conn);
- }
- } else {
- throw new IOException("Authentication Error: " + status);
- }
- } catch (IOException i) {
- i.printStackTrace();
- Log.e("IO Exception - ", i.toString());
- }
- } else {
- result = "No File detected";
- }
- return result;
- }
- public void upload(HttpURLConnection conn) {
- try {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
- String formattedDate = sdf.format(new Date());
- conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "multipart/form-data");
- conn.setRequestProperty("X-OpenRosa-Version", "1.0");
- conn.setRequestProperty("Date", formattedDate);
- conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Cache-Control", "no-cache");
- conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
- OutputStream outputStream = conn.getOutputStream();
- PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8").newEncoder()), true);
- writer.append(twoHyphens + boundary + crlf);
- writer.append("Content-Disposition: form-data; name=\"xml_submission_file\"; filename=\"" + formName + "\"" + crlf);
- writer.append("Content-Type: text/xml;" + crlf + crlf);
- writer.flush();
- FileInputStream inputStream = new FileInputStream(file);
- byte[] buffer = new byte[4096];
- int bytesRead = -1;
- while ((bytesRead = inputStream.read(buffer)) != -1) {
- outputStream.write(buffer, 0, bytesRead);
- }
- outputStream.flush();
- inputStream.close();
- writer.append(crlf);
- writer.flush();
- writer.append(crlf);
- writer.flush();
- writer.append(twoHyphens + boundary + twoHyphens);
- writer.append(crlf);
- String post = writer.toString();
- writer.close();
- // Check server response
- String debug = "";
- int status = conn.getResponseCode();
- if (status == HttpURLConnection.HTTP_OK) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line = null;
- while ((line = reader.readLine()) != null) {
- debug = debug + line;
- }
- reader.close();
- conn.disconnect();
- } else {
- throw new IOException("Server returned non-OK status: " + status + " " + post);
- }
- } catch (MalformedURLException m) {
- m.printStackTrace();
- Log.e("URL Exception - ", m.toString());
- } catch (IOException i) {
- i.printStackTrace();
- Log.e("IO Exception - ", i.toString());
- }
- }
- public static HttpURLConnection tryDigestAuthentication(HttpURLConnection input, String username, String password) {
- String auth = input.getHeaderField("WWW-Authenticate");
- if(auth == null || !auth.startsWith("Digest ")){
- return null;
- }
- final HashMap<String, String> authFields = splitAuthFields(auth.substring(7));
- MessageDigest md5 = null;
- try{
- md5 = MessageDigest.getInstance("MD5");
- } catch(NoSuchAlgorithmException e){
- return null;
- }
- String j = ":";
- String HA1 = null;
- try{
- md5.reset();
- String ha1str = username + j + authFields.get("realm") + j + password;
- md5.update(ha1str.getBytes("ISO-8859-1"));
- byte[] ha1bytes = md5.digest();
- HA1 = bytesToHexString(ha1bytes);
- } catch(UnsupportedEncodingException e){
- return null;
- }
- String HA2 = null;
- try{
- md5.reset();
- String ha2str = (input.getRequestMethod() + j + input.getURL().getPath());
- md5.update(ha2str.getBytes("ISO-8859-1"));
- HA2 = bytesToHexString(md5.digest());
- } catch(UnsupportedEncodingException e){
- return null;
- }
- String HA3 = null;
- String cnoice = generateCNonce();
- try{
- md5.reset();
- String ha3str = (HA1 + j + authFields.get("nonce") + j + "1" + cnoice + "auth" + HA2);
- md5.update(ha3str.getBytes("ISO-8859-1"));
- HA3 = bytesToHexString(md5.digest());
- } catch(UnsupportedEncodingException e){
- return null;
- }
- StringBuilder sb = new StringBuilder(128);
- sb.append("Digest ");
- sb.append("username").append("=\"").append(username).append("\", ");
- sb.append("realm").append("=\"").append(authFields.get("realm")).append("\", ");
- sb.append("nonce").append("=\"").append(authFields.get("nonce")).append("\", ");
- sb.append("uri").append("=\"").append(input.getURL().getPath()).append("\", ");
- sb.append("response").append("=\"").append(HA3).append("\", ");
- sb.append("qop").append('=').append("auth").append(", ");
- sb.append("nc").append("=\"").append("1").append("\", ");
- sb.append("cnonce").append("=\"").append(cnoice).append("\"");
- //sb.append("algorithm").append("=\"").append(authFields.get("algorithm")).append("\"");
- try{
- final HttpURLConnection result = (HttpURLConnection)input.getURL().openConnection();
- result.addRequestProperty("Authorization", sb.toString());
- return result;
- }
- catch(IOException e){
- return null;
- }
- }
- private static HashMap<String, String> splitAuthFields(String authString)
- {
- final HashMap<String, String> fields = Maps.newHashMap();
- final CharMatcher trimmer = CharMatcher.anyOf("\"\t ");
- final Splitter commas = Splitter.on(',').trimResults().omitEmptyStrings();
- final Splitter equals = Splitter.on('=').trimResults(trimmer).limit(2);
- String[] valuePair;
- for(String keyPair : commas.split(authString)){
- valuePair = Iterables.toArray(equals.split(keyPair), String.class);
- fields.put(valuePair[0], valuePair[1]);
- }
- return fields;
- }
- private static final String HEX_LOOKUP = "0123456789abcdef";
- private static String bytesToHexString(byte[] bytes)
- {
- StringBuilder sb = new StringBuilder(bytes.length * 2);
- for(int i = 0; i < bytes.length; i++){
- sb.append(HEX_LOOKUP.charAt((bytes[i] & 0xF0) >> 4));
- sb.append(HEX_LOOKUP.charAt((bytes[i] & 0x0F) >> 0));
- }
- return sb.toString();
- }
- public static class AuthenticationException extends IOException
- {
- private static final long serialVersionUID = 1L;
- public AuthenticationException()
- {
- super("Problems authenticating");
- }
- }
- private static String generateCNonce() {
- String s = "";
- for (int i = 0; i < 8; i++)
- s += Integer.toHexString(new Random().nextInt(16));
- return s;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement