UnknownHostException WebDav JackRabbit

Я пытаюсь реализовать клиент WebDav на Android. Для этого я использую версию JackRabbit, модифицированную для Android, которую я получил здесь (версия 2.2.6).

Я хочу подключиться к своей учетной записи на box.com и загрузить файл. С уважением, я не возражаю против коробки или любого другого, я просто случайно воспользовался этим.

Что ж, продолжая box.com, согласно (эта ссылка) [https://support.box.com/hc/en-us/articles/200519748-Does-Box-support-WebDAV-] Я должен использовать "https://dav.box.com/dav" в качестве сервера.

Я перешел по этим ссылкам, чтобы создать свой код:

Я получаю исключение UnknownHostException с указанием URL-адреса, который я использую для сервера ("https://dav.box.com/dav ") не удалось найти.

Есть идеи, почему это не работает? В противном случае, пробовали ли вы с другим сервером и преуспели?

Мой код здесь:

Thread t = new Thread() {
        public void run(){
            try {
                String uri = "https://app.box.com/files";
                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(uri);

                HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
                HttpConnectionManagerParams params = new HttpConnectionManagerParams();
                int maxHostConnections = 20;
                params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
                connectionManager.setParams(params);

                HttpClient client = new HttpClient(connectionManager);
                client.setHostConfiguration(hostConfig);
                Credentials creds = new UsernamePasswordCredentials("USER", "PASSWORD");
                client.getState().setCredentials(AuthScope.ANY, creds);

                String baseUrl = "/";
                File f = new File(Environment.getExternalStorageDirectory() + "/working-draft.txt");
                PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
                RequestEntity requestEntity = new InputStreamRequestEntity(
                    new FileInputStream(f));
                method.setRequestEntity(requestEntity);
                client.executeMethod(method);
            }
            catch (FileNotFoundException fnfe){
                Log.i("SERVICE", "FileNotFoundException");
            }
            catch (HttpException he){
                Log.i("SERVICE", "HttpException");
            }
            catch (IOException ioe){
                Log.i("SERVICE", "IOException");
            }
            catch (Exception e){
                Log.i("SERVICE", "Other Exception");
            }
        }
    };
    t.start();

person Fernando    schedule 20.01.2015    source источник


Ответы (1)


Я долгое время пробовал использовать JackRabbit и другую библиотеку webDav, но не мог заставить ее работать. Вот как мне в конечном итоге удалось отправить изображения в WebDav, размещенный в IIS7 на сервере Windows. Надеюсь, это кому-то поможет.

SendImage.java

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import ntlm.NTLMSchemeFactory;

//import org.apache.http.client.HttpClient;

public class SendImage extends AsyncTask<String, Context, String> {
    Context cxt;

    public SendImage(Context cxtIn){
        cxt = cxtIn;
    }

    @Override
    protected String doInBackground(String... params) {
        if (!Globals.sendImagesBeingPerformed) {

            Globals.sendImagesBeingPerformed = true;
            String filepath = cxt.getExternalFilesDir("/MyFileStorage/qrscans/").getAbsolutePath();
            File myExternalFile = new File(filepath.toString());
            File[] sdDirList = myExternalFile.listFiles();

            if(sdDirList != null && sdDirList.length>0){
                for(int x=0;x<sdDirList.length;x++){
                    if(sdDirList[x].toString().endsWith(".jpg")){

                        File myExternalFile2 = new File(cxt.getExternalFilesDir("/MyFileStorage/qrscans/"), sdDirList[x].getName());
                        //String URL="";
                        System.out.println("SENDING QR4");
                        if(myExternalFile2.exists()) {
                            System.out.println("ScannedExists");
                            DefaultHttpClient httpclient = new DefaultHttpClient();
                            httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());

                            String url = Globals.getWebDavUrl().trim();
                            String u = Globals.getWebDavUser().trim();
                            String p = Globals.getWebDavPass().trim();
                            String d = Globals.getWebDavDomain().trim();
                            if(d!=null && !d.isEmpty() && (d.length()>0)){
                                //use value of d as domain
                            }else{
                                //use a space as domain
                                d = " ";
                            }

                            String device = Globals.deviceId;
                            httpclient.getCredentialsProvider().setCredentials(
                                    new AuthScope(null, -1),
                                    new NTCredentials(u, p, device, d));
                            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),5000);

                            if(url.endsWith("/") || url.endsWith("\\")){
                                url = url.substring(0, url.length()-1);
                            }

                            HttpPut put = new HttpPut(url.trim()+"/"+sdDirList[x].getName());
                            put.setEntity(new FileEntity(sdDirList[x],"application/octet-stream"));
                            HttpResponse response = null;

                            try {
                                response = httpclient.execute(put);
                            }catch(Exception e){
                                return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
                            }
                            System.out.println("execute done");

                            BufferedReader in = null;
                            String webResponse="";
                            try {
                                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                                String stringLine="";
                                StringBuilder stringBuilder = new StringBuilder();
                                while ((stringLine = in.readLine()) != null) {
                                    //stringBuilder.append("\n");
                                    stringBuilder.append(stringLine);
                                }
                                webResponse=stringBuilder.toString()+"s";
                                if(webResponse.toString().trim().equalsIgnoreCase("s")){
                                    myExternalFile2.delete();
                                }

                                System.out.println("webResponse:" + webResponse);
                                return null; //webResponse;
                            }catch(Exception e){
                                return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        if(result!=null){
            Toast.makeText(cxt, result, Toast.LENGTH_LONG).show();
        }

        Globals.sendImagesBeingPerformed = false;


super.onPostExecute(result);
        }
    }

NTLMSchemeFactory.java

import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.params.HttpParams;

public class NTLMSchemeFactory implements AuthSchemeFactory {

    public AuthScheme newInstance(final HttpParams params) {
        return new NTLMScheme(new JCIFSEngine());
    }

}

JCIFSEngine.java

package ntlm;

import java.io.IOException;

import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;

import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;

public class JCIFSEngine implements NTLMEngine {

    public String generateType1Msg(
            String domain, 
            String workstation) throws NTLMEngineException {

        Type1Message t1m = new Type1Message(
                Type1Message.getDefaultFlags(),
                domain,
                workstation);
        return Base64.encode(t1m.toByteArray());
    }

    public String generateType3Msg(
            String username, 
            String password, 
            String domain,
            String workstation, 
            String challenge) throws NTLMEngineException {
        Type2Message t2m;
        try {
            t2m = new Type2Message(Base64.decode(challenge));
        } catch (IOException ex) {
            throw new NTLMEngineException("Invalid Type2 message", ex);
        }
        Type3Message t3m = new Type3Message(
                t2m, 
                password, 
                domain, 
                username, 
                workstation,0);
        return Base64.encode(t3m.toByteArray());
    }

}
person matty357    schedule 14.08.2015