请看Java PUT示例

时间:2012-05-07 21:30:15

标签: java desire2learn

我正在尝试将用户更新发送到valance,我正在寻找一个如何进行put的示例,特别是更新用户的put。

我环顾四周,但没有看到如何使用UserContext使用Java发送json块的示例。

任何指向文档的指针都将受到赞赏。

2 个答案:

答案 0 :(得分:1)

在对此进行修补之后,我的同事提出了许多建议(我不确定是谁,所以我只是称他为比尔)。我们提出了以下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;
}

答案 1 :(得分:0)

我可以从使用api的项目中共享一个php代码片段(与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": "me@somehostname.com",
"UserName": "Username",
"Activation": {
        "IsActive": true
}
}