HttpURLConnection в Java не поддерживает REPORT / PROPFIND - что мне делать? - PullRequest
6 голосов
/ 11 августа 2010

HttpURLConnection поддерживает только такие вещи, как GET, POST и HEAD - но не REPORT / PROPFIND.Я собираюсь реализовать CalDAV-Client, но без этих операций (если я хочу их использовать, я получаю ProtocolException), я должен написать / доставить полную и огромную HTTP-библиотеку с аутентификацией и т. Д.

"Overkill".

Как отправлять запросы с PROPFIND и REPORT?

Ответы [ 6 ]

4 голосов
/ 26 августа 2014

У меня была похожая проблема в WebDav для метода PROPFIND.

Решил проблему путем реализации этого решения: 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);

            }
     }
3 голосов
/ 18 февраля 2016

Либо вы можете использовать https://github.com/square/okhttp

Пример кода

    // 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();
    }
 }

Или играть с розетками

Пример кода

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();
3 голосов
/ 11 августа 2010

Возможно, вы захотите поискать библиотеку WebDAV, а не библиотеку HTTP, для этого.

Возможно, взгляните на Apache Jackrabbit .

2 голосов
/ 11 августа 2010

Вы можете попробовать использовать другую HTTP-библиотеку, такую ​​как Apache HTTP-клиент и расширить его HttpRequestBase (см., Например, HttpGet и HttpPost).

Кроме того, вы можете напрямую использовать клиентскую библиотеку WebDAV.

0 голосов
/ 03 апреля 2017
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);
        }
    }
}
0 голосов
/ 01 марта 2011

Рассмотрите возможность использования Caldav4j

. Поддерживает:

  • простое создание запросов отчетов
  • на основе httpclient 3.0
  • Android-приложение
  • в настоящее время мигрирует на кролика
...