400 错误请求无效动词 SharePoint 休息 Api Java

400 Bad Request Invalid Verb SharePoint Rest Api Java

我正在尝试 post 向 SharePoint REST 界面发出请求。我正在尝试更新列值。当我 post 使用 Fiddler (Response: 204) 时,我能够成功地做到这一点。当我使用 Apache HttpClient 发送时,我收到 400 Bad Request - Invalid Verb.

附带说明一下,当我尝试使用 Fiddler 作为此程序的代理(本地主机,端口 8888)时,请求成功。但是当我再次删除代理并尝试时,它是不成功的。我的 Java 代码有问题吗?

这是通过 HTTP post 发送 JSON 字符串的方式吗?

private static final String API_ENDPOINT = "/_api/web";
    private static final String CONTEXT_INFO_ENDPOINT = "/_api/contextinfo";
    private static final String APPLICATION_JSON = "application/json;odata=verbose";
    private static final String IF_MATCH = "If-Match";
    private static final String X_HTTP_Method = "X-HTTP-Method";
    private static final String MERGE = "MERGE";
    private static final String X_RequestDigest = "X-RequestDigest";
    private static final String METADATA = "__metadata";

    public static boolean setFieldValue(CloseableHttpClient httpClient, String siteURL, String serverRelativeURL, String fieldName, String fieldValue, String fieldType) {

    CloseableHttpResponse response = null;

    try {
        URI siteURI = new URI(siteURL);
        URI postURI = new URIBuilder(siteURI)
                .setPath(siteURI.getPath() + API_ENDPOINT + "/GetFileByServerRelativeUrl('" + serverRelativeURL + "')/ListItemAllFields")
                .build();
        HttpPost postRequest = new HttpPost(postURI);

        postRequest.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON );
        postRequest.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
        postRequest.addHeader(HttpHeaders.HOST, siteURI.getHost());
        postRequest.addHeader(IF_MATCH, "*");
        postRequest.addHeader(X_HTTP_Method, MERGE);

        String formDigestValue = getFormDigestValue(httpClient, siteURI);
        if (StringUtils.isBlank(formDigestValue)) {
            logger.error("FORM DIGEST VALUE IS = " + formDigestValue);
            return false;
        }
        postRequest.addHeader(X_RequestDigest, formDigestValue);

        JSONObject type = new JSONObject();
        type.put("type", fieldType);

        JSONObject jsonBody = new JSONObject();
        jsonBody.put(METADATA , type);
        jsonBody.put(fieldName, fieldValue);


        logger.debug("setFieldValue(): " + jsonBody.toString());
        postRequest.setEntity(new StringEntity(jsonBody.toString()));
        //String jsonString = "{'__metadata':{'type':'SP.Data.NextlabsDLItem'},'TextHeader':'Java1'}";
        //JSONObject jsonObject = new JSONObject(jsonString);
        //logger.debug(jsonObject);
        //postRequest.setEntity(new ByteArrayEntity(jsonBody.toString().getBytes(), ContentType.APPLICATION_JSON));
        logger.debug("setFieldValue(): " + postRequest.getRequestLine());

        response = httpClient.execute(postRequest);

        logger.debug("setFieldValue(): " + response.getStatusLine());

        int status = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
        int cp;
        StringBuilder sb = new StringBuilder();
        while ((cp = bufferedReader.read()) != -1) {
            sb.append((char) cp);
        }
        logger.debug("String Response......." + sb);
        bufferedReader.close();
        if (status >= 200 && status < 300) {
            return true;
        } else {
            logger.error("setFieldValue(): " + response.getStatusLine().toString().toUpperCase());
        }

    } catch (URISyntaxException | IOException e) {
        logger.error("setFieldValue(): " + e.getMessage(), e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;

}

很抱歉张贴了我自己的答案,但终于找到了问题。

错误是 ExpectContinuedFlag 在 apache HTTPClient 中启用。

我在 HTTP 初始化中更改了以下内容,现在可以使用了!

    RequestConfig requestConfig = RequestConfig.custom()
            .setExpectContinueEnabled(***false***)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
            .build();

    return HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultCredentialsProvider(creds)
            .setDefaultRequestConfig(requestConfig)
            .build();