Пример Java PUT, пожалуйста

Я пытаюсь отправить обновление пользователя в valance, и я ищу пример того, как сделать пут, в частности, пут для обновления пользователя.

Я осмотрелся, но не вижу примера того, как использовать UserContext для отправки блока json с помощью Java.

Любые указатели на документацию будут оценены.


person Glenn Watt    schedule 07.05.2012    source источник


Ответы (2)


После возни с этим и с большим количеством предложений от моего коллеги (который, я не уверен, хочет быть названным, поэтому я буду называть его просто Билл). Мы придумали следующий метод Java (на самом деле нужно разделить на отдельные методы, но это понятно)

private static String getValanceResult(ID2LUserContext userContext,
        URI uri, String query, String sPost, String sMethod, int attempts) {

    String sError = "Error: An Unknown Error has occurred";
    if (sMethod == null) {
        sMethod = "GET";
    }

    URLConnection connection;
    try {
        URL f = new URL(uri.toString() + query);

        //connection = uri.toURL().openConnection();
        connection = f.openConnection();
    } catch (NullPointerException e) {
        return "Error: Must Authenticate";
    } catch (MalformedURLException e) {
        return "Error: " + e.getMessage();
    } catch (IOException e) {
        return "Error: " + e.getMessage();
    }


    StringBuilder sb = new StringBuilder();

    try {
        // cast the connection to a HttpURLConnection so we can examin the
        // status code
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        httpConnection.setRequestMethod(sMethod);
        httpConnection.setConnectTimeout(20000);
        httpConnection.setReadTimeout(20000);
        httpConnection.setUseCaches(false);
        httpConnection.setDefaultUseCaches(false);
        httpConnection.setDoOutput(true);


        if (!"".equals(sPost)) {
            //setup connection
            httpConnection.setDoInput(true);
            httpConnection.setRequestProperty("Content-Type", "application/json");


            //execute connection and send xml to server
            OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream());
            writer.write(sPost);
            writer.flush();
            writer.close();
        }

        BufferedReader in;
        // if the status code is success then the body is read from the
        // input stream
        if (httpConnection.getResponseCode() == 200) {
            in = new BufferedReader(new InputStreamReader(
                    httpConnection.getInputStream()));
            // otherwise the body is read from the output stream
        } else {
            in = new BufferedReader(new InputStreamReader(
                    httpConnection.getErrorStream()));
        }

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sb.append(inputLine);
        }
        in.close();

        // Determine the result of the rest call and automatically adjusts
        // the user context in case the timestamp was invalid
        int result = userContext.interpretResult(
                httpConnection.getResponseCode(), sb.toString());
        if (result == ID2LUserContext.RESULT_OKAY) {
            return sb.toString();
            // if the timestamp is invalid and we haven't exceeded the retry
            // limit then the call is made again with the adjusted timestamp
        } else if (result == userContext.RESULT_INVALID_TIMESTAMP
                && attempts > 0) {
            return getValanceResult(userContext, uri, query, sPost, sMethod, attempts - 1);
        } else {
            sError = sb + " " + result;
        }
    } catch (IllegalStateException e) {
        return "Error: Exception while parsing";
    } catch (FileNotFoundException e) {
        // 404
        return "Error: URI Incorrect";
    } catch (IOException e) {
    }
    return sError;
}
person Glenn Watt    schedule 14.05.2012

Есть фрагмент кода php, которым я могу поделиться из проекта, использующего API (такая же грубая логика с java). Контекст пользователя просто подготавливает URL-адрес, а структура конкретной среды (среда выполнения Java или библиотека php) используется для публикации и получения результатов (в данном случае используется php CURL).

        $apiPath = "/d2l/api/le/" . VERSION. "/" . $courseid . "/content/isbn/";
        $uri = $opContext->createAuthenticatedUri ($apiPath, 'POST');
        $uri = str_replace ("https", "http", $uri);
        curl_setopt ($ch, CURLOPT_URL, $uri);
        curl_setopt ($ch, CURLOPT_POST, true);

        $response = curl_exec ($ch);
        $httpCode = curl_getinfo ($ch, CURLINFO_HTTP_CODE);
        $contentType = curl_getinfo ($ch, CURLINFO_CONTENT_TYPE);
        $responseCode = $opContext->handleResult ($response, $httpCode, $contentType);

        $ret = json_decode($response, true);

        if ($responseCode == D2LUserContext::RESULT_OKAY)
        {
            $ret = "$response";
            $tryAgain = false;
        }
        elseif ($responseCode == D2LUserContext::RESULT_INVALID_TIMESTAMP)
        {
            $tryAgain = true;
        }
        elseif (isset ($ret['Errors'][0]['Message']))
        {
            if ($ret['Errors'][0]['Message'] == "Invalid ISBN")
            {
                $allowedOrgId[] = $c;
            }
            $tryAgain = false;
        }

Пример трассировки почтового сообщения:

PUT https://valence.desire2learn.com/d2l/api/lp/1.0/users/3691?x_b=TwULqrltMXvTE8utuLCN5O&x_a=L2Hd9WvDTcyiyu5n2AEgpg&x_d=OKuPjV-a0ZoSBuZvJkQLpFva2D59gNjTMiP8km6bdjk&x_c=UjCMpy1VNHsPCJOjKAE_92g1YqSxmebLHnQ0cbhoSPI&x_t=1336498251 HTTP/1.1
Accept-Encoding: gzip,deflate
Accept: application/json
Content-Type: application/json

{
"OrgDefinedId": "85033380",
"FirstName": "First",
"MiddleName": "Middle",
"LastName": "Last",
"ExternalEmail": "[email protected]",
"UserName": "Username",
"Activation": {
        "IsActive": true
}
}
person Cadmium    schedule 08.05.2012
comment
Спасибо, в настоящее время я не работаю с PHP, но похоже, что это тоже поможет. - person Glenn Watt; 15.05.2012