2017-02-14 39 views
1

Я пытаюсь обновить поле внутри библиотеки документов Sharepoint, используя Apache HTTPClient, но продолжаю получать HTTP-ошибку 400 - Недопустимый URL-адрес. Код и вывод приведены ниже. Просьба сообщить, почему это происходитПолучение ошибки HTTP 400 Bad Request - недопустимый URL-адрес при попытке обновления поля SharePoint

Document Library Image

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

    CloseableHttpResponse httpResponse = null; 

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

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

     httpPost.addHeader(ACCEPT, APPLICATION_JSON); 
     httpPost.addHeader(CONTENT_TYPE, APPLICATION_JSON); 
     httpPost.addHeader(X_HTTP_Method, MERGE); 
     httpPost.addHeader(IF_MATCH, Punctuation.ASTERISK); 
     httpPost.addHeader(X_REQUEST_DIGEST, formDigestValue); 

     JSONObject jsonObject = new JSONObject(); 
     jsonObject.put(fieldName, fieldValue); 
     jsonObject.put("__metadata", new JSONObject().put("type", "SP.Data.PuneetsLibraryItem")); 
     logger.debug(jsonObject); 

     httpPost.setEntity(new StringEntity(jsonObject.toString())); 

     logger.trace(httpPost.getRequestLine()); 
     logger.trace(httpPost.getURI()); 

     httpResponse = httpClient.execute(httpPost); 

     HttpEntity entity = httpResponse.getEntity(); 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); 
     if (bufferedReader != null) { 
      int cp; 
      StringBuilder sb = new StringBuilder(); 
      while ((cp = bufferedReader.read()) != -1) { 
       sb.append((char) cp); 
      } 
      logger.debug("String Response......." + sb); 
      bufferedReader.close(); 
     } 
     logger.debug("Response......." + entity.getContent()); 

     logger.trace(httpResponse.getStatusLine().getReasonPhrase()); 

     int status = httpResponse.getStatusLine().getStatusCode(); 
     if (status >= 200 && status < 300) { 
      return true; 
     } else { 
      logger.error("ERROR: " + httpResponse.getStatusLine().toString().toUpperCase()); 
     } 

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

} 

консоли Журналы:

13:57:44.089 [main] DEBUG com.nextlabs.smartclassifier.sharepoint.SharePointUtil - POST http://sp2013w2k12r2/_api/contextinfo HTTP/1.1 
13:57:45.417 [main] TRACE com.nextlabs.smartclassifier.sharepoint.SharePointUtil - HTTP/1.1 200 OK 
13:57:45.417 [main] DEBUG com.nextlabs.smartclassifier.sharepoint.SharePointUtil - {"TestField":"Puneet","__metadata":{"type":"SP.Data.PuneetsLibraryItem"}} 
13:57:45.433 [main] TRACE com.nextlabs.smartclassifier.sharepoint.SharePointUtil - POST http://sp2013w2k12r2/_api/web/GetFileByServerRelativeUrl('/PuneetsLibrary/Three.docx')/ListItemAllFields HTTP/1.1 
13:57:45.433 [main] TRACE com.nextlabs.smartclassifier.sharepoint.SharePointUtil - http://sp2013w2k12r2/_api/web/GetFileByServerRelativeUrl('/PuneetsLibrary/Three.docx')/ListItemAllFields 
13:57:45.448 [main] DEBUG com.nextlabs.smartclassifier.sharepoint.SharePointUtil - String Response.......<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> 
<HTML><HEAD><TITLE>Bad Request</TITLE> 
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD> 
<BODY><h2>Bad Request - Invalid URL</h2> 
<hr><p>HTTP Error 400. The request URL is invalid.</p> 
</BODY></HTML> 

13:57:45.448 [main] DEBUG com.nextlabs.smartclassifier.sharepoint.SharePointUtil - [email protected]5 
13:57:45.448 [main] TRACE com.nextlabs.smartclassifier.sharepoint.SharePointUtil - Bad Request 
13:57:45.448 [main] ERROR com.nextlabs.smartclassifier.sharepoint.SharePointUtil - ERROR: HTTP/1.1 400 BAD REQUEST 
13:57:45.448 [main] INFO com.nextlabs.smartclassifier.util.HTTPClientUtil - Trying to close HTTP Connections 
13:57:45.448 [main] INFO com.nextlabs.smartclassifier.util.HTTPClientUtil - HTTP Connections closed successfully. 
+0

вы можете попробовать напечатать URL –

+0

@pushpendra URL-адрес печатается в журналах консоли. – Puneet

+0

Вы видели этот ответ http://stackoverflow.com/questions/21383707/sp-web-getfilebyserverrelativeurlfileurl-not-working –

ответ

0

я понял свою ошибку, так я отправляю ответ. HttpClient отправил в запрос поле заголовка expect, которое он не должен отправлять. Также X-Request-Digest пришлось заменить на X-RequestDigest.

Путь отключить заголовок ожидать следующим образом:

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

httpclient = HttpClients.custom() 
     .setConnectionManager(httpClientConnectionManager) 
     .setDefaultCredentialsProvider(credentialsProvider) 
     .setDefaultRequestConfig(defaultRequestConfig) 
     //.setConnectionTimeToLive(1, TimeUnit.MINUTES) 
     .build();