2010-08-11 5 views

Respuesta

3

Probablemente desee buscar una biblioteca WebDAV, no una biblioteca HTTP, para esta.

Tal vez eche un vistazo a Apache Jackrabbit.

+0

+1 para el enlace de liebre, aunque el enlace que has enviado es para el lado del servidor. Esto podría ser más directamente relevante: http://jackrabbit.apache.org/api/1.3/org/apache/jackrabbit/webdav/client/methods/package-summary.html – Bruno

2

Se podría tratar de utilizar otra biblioteca HTTP, como Apache HTTP client y extender su HttpRequestBase (ver HttpGet y HttpPost por ejemplo).

Como alternativa, puede utilizar una biblioteca de cliente WebDAV directamente.

0

considerar el uso de Caldav4j

Es compatible con:

  • fácil generación de informe solicita
  • basado en httpclient 3.0
  • aplicación Android
  • migración actualmente a JackRabbit
3

Tuve un problema similar en WebDav para el método PROPFIND.

resuelto el problema mediante la implementación de esta solución: https://java.net/jira/browse/JERSEY-639

try { 
      httpURLConnection.setRequestMethod(method); 
     } catch (final ProtocolException pe) { 
      try { 
       final Class<?> httpURLConnectionClass = httpURLConnection 
         .getClass(); 
       final Class<?> parentClass = httpURLConnectionClass 
         .getSuperclass(); 
       final Field methodField; 
       // If the implementation class is an HTTPS URL Connection, we 
       // need to go up one level higher in the heirarchy to modify the 
       // 'method' field. 
       if (parentClass == HttpsURLConnection.class) { 
        methodField = parentClass.getSuperclass().getDeclaredField(
          "method"); 
       } else { 
        methodField = parentClass.getDeclaredField("method"); 
       } 
       methodField.setAccessible(true); 
       methodField.set(httpURLConnection, method); 
      } catch (final Exception e) { 
       throw new RuntimeException(e); 

      } 
    } 
+1

¡Buena respuesta! Sin embargo, en mi caso, httpURLConnection tiene un delegado y la respuesta no funciona. Por lo tanto, extraigo el campo de delegado del objeto httpURLConnection por reflexión. El campo delegado también es la (sub sub) subclase de HttpURLConnection. Aplico su procedimiento para esta conexión delegada por methodField = parentClass.getSuperclass(). GetSuperclass(). GetDeclaredField ("method") ;. Esto funciona bien ¡Gracias! – KNaito

+0

Probé la solución anterior y obtuve erro como "método http no permitido". Podrías dar cualquier indicación sobre esto.También veo que httpURLConnection tiene un delegado, pero cuando probé la solución comentada, recibí el error noSuchMethod. – Dhamayanthi

+0

@KNaito podría por favor me ayude a solucionar este problema, estoy usando JDK 1.7 y directamente usando HttpURLConnection – Dhamayanthi

3

O se puede utilizar https://github.com/square/okhttp

Código de ejemplo

// using OkHttp 
    public class PropFindExample {   
    private final OkHttpClient client = new OkHttpClient(); 
    String run(String url) throws IOException { 
     String credential = Credentials.basic(userName, password); 
     // body 
     String body = "<d:propfind xmlns:d=\"DAV:\" xmlns:cs=\"http://calendarserver.org/ns/\">\n" + 
       " <d:prop>\n" + 
       "  <d:displayname />\n" + 
       "  <d:getetag />\n" + 
       " </d:prop>\n" + 
       "</d:propfind>"; 
     Request request = new Request.Builder() 
       .url(url) 
       .method("PROPFIND", RequestBody.create(MediaType.parse(body), body)) 
       .header("DEPTH", "1") 
       .header("Authorization", credential) 
       .header("Content-Type", "text/xml") 
       .build(); 

     Response response = client.newCall(request).execute(); 
     return response.body().string(); 
    } 
} 

O jugar con sockets

Código de ejemplo

String host = "example.com"; 
int port = 443; 
String path = "/placeholder"; 
String userName = "username"; 
String password = "password"; 

SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); 
Socket socket = ssf.createSocket(host, port); 
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); 

// xml data to be sent in body 
String xmlData = "<?xml version=\"1.0\"?> <d:propfind xmlns:d=\"DAV:\" xmlns:cs=\"http://calendarserver.org/ns/\"> <d:prop> <d:displayname /> <d:getetag /> </d:prop> </d:propfind>"; 
// append headers 
out.println("PROPFIND path HTTP/1.1"); 
out.println("Host: "+host); 
String userCredentials = username+":"+password; 
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes(), Base64.DEFAULT)); 
String authorization = "Authorization: " + basicAuth; 
out.println(authorization.trim()); 
out.println("Content-Length: "+ xmlData.length()); 
out.println("Content-Type: text/xml"); 
out.println("Depth: 1"); 
out.println(); 
// append body 
out.println(xmlData); 
out.flush(); 

// get response 
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
String inputLine; 

System.out.println("--------------------------------------------------------"); 
System.out.println("---------------Printing response--------------------------"); 
System.out.println("--------------------------------------------------------"); 
while ((inputLine = in.readLine()) != null) { 
    System.out.println(inputLine); 
} 

in.close(); 
+0

No lo copie/pegue (http://stackoverflow.com/a/35490228/189134) la misma respuesta a múltiples preguntas. En su lugar, personalice la respuesta a las preguntas individuales y explique cómo resuelven ese problema en particular. – Andy

+0

¡Claro! ¡Gracias por tu mensaje! –

0
private static void setRequestMethod(HttpURLConnection conn, String method) throws Throwable { 
    try { 
     conn.setRequestMethod(method); 
    } catch (ProtocolException e) { 
     Class<?> c = conn.getClass(); 
     Field methodField = null; 
     Field delegateField = null; 
     try { 
      delegateField = c.getDeclaredField("delegate"); 
     } catch (NoSuchFieldException nsfe) { 

     } 
     while (c != null && methodField == null) { 
      try { 
       methodField = c.getDeclaredField("method"); 
      } catch (NoSuchFieldException nsfe) { 

      } 
      if (methodField == null) { 
       c = c.getSuperclass(); 
      } 
     } 
     if (methodField != null) { 
      methodField.setAccessible(true); 
      methodField.set(conn, method); 
     } 

     if (delegateField != null) { 
      delegateField.setAccessible(true); 
      HttpURLConnection delegate = (HttpURLConnection) delegateField.get(conn); 
      setRequestMethod(delegate, method); 
     } 
    } 
} 
Cuestiones relacionadas