Java : Update a docx file on Sharepoint online with Graph API - java

I have an issue updating a docx file on Sharepoint online with Java.
First I checked the URL to build the PUT request (here : https://learn.microsoft.com/fr-fr/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http) and use this request : PUT /drives/{drive-id}/items/{item-id}/content
I first use service to build the URL :
#Override
public UpdateDocumentResponseModel updateDocument(String accessToken, String libId, String docId, String filePath) throws MalformedURLException {
URL url = new URL("https://graph.microsoft.com/v1.0/drives/" + libId + "/items/" + docId + "/content");
return documentRequestBuilder.updateDocument(accessToken, url, filePath);
}
I build the request :
public UpdateDocumentResponseModel updateDocument(String accessToken, URL url, String fullPath) {
UpdateDocumentResponseModel returnValue = new UpdateDocumentResponseModel();
Tika tika = new Tika();
String mimeType = tika.detect(fullPath);
System.out.println("Test mime type: " + mimeType);
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(String.valueOf(url));
httpPut.setHeader("Authorization", "Bearer " + accessToken);
httpPut.setHeader("Content-Type", mimeType);
httpPut.setHeader("Connection", "Keep-Alive");
httpPut.setHeader("Cache-Control", "no-cache");
// read the file and convert to stream
// Get an input stream for the file
InputStream in = new FileInputStream(fullPath);
httpPut.setEntity(new StringEntity(String.valueOf(in), StandardCharsets.UTF_8));
CloseableHttpResponse response = client.execute(httpPut);
System.out.println("\nSending 'PUT' request to URL : " + url);
System.out.println("Response Code : " + response.getStatusLine());
// set the response
returnValue.setDocumentName(fullPath);
returnValue.setUpdatedAt(new Date());
returnValue.setUpdateStatus("Success");
} catch (IOException e) {
returnValue.setDocumentName(fullPath);
returnValue.setUpdatedAt(new Date());
returnValue.setUpdateStatus("Failure" + e.getCause());
e.printStackTrace();
}
return returnValue;
}
I can note that the file is updated in Sharepoint.
I build the response :
Update a document by Id and DriveId
{
"documentName" : "C:\\Users\\me\\Documents\\uploadFolder\\myDoc.docx",
"updateStatus" : "Success",
"updatedAt" : 1590147553641
}
Unfortunatelly, the file can't be opened.

I finally solved the issue by using ByteArrayInputStream...
public UpdateDocumentResponseModel updateDocument(String accessToken, URL url, String fullPath) {
UpdateDocumentResponseModel returnValue = new UpdateDocumentResponseModel();
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(String.valueOf(url));
httpPut.setHeader("Authorization", "Bearer " + accessToken);
httpPut.setHeader("Content-Type", "text/plain");
httpPut.setHeader("Connection", "Keep-Alive");
httpPut.setHeader("Cache-Control", "no-cache");
byte[] fileContent = FileUtils.readFileToByteArray(new File(fullPath));
httpPut.setEntity(new InputStreamEntity(new ByteArrayInputStream(fileContent), fileContent.length));
// httpPut.setEntity(new StringEntity(String.valueOf(in), StandardCharsets.UTF_8));
CloseableHttpResponse response = client.execute(httpPut);
System.out.println("\nSending 'PUT' request to URL : " + url);
System.out.println("Response Code : " + response.getStatusLine());
// set the response
returnValue.setDocumentName(fullPath);
returnValue.setUpdatedAt(new Date());
returnValue.setUpdateStatus("Success");
} catch (IOException e) {
returnValue.setDocumentName(fullPath);
returnValue.setUpdatedAt(new Date());
returnValue.setUpdateStatus("Failure" + e.getCause());
e.printStackTrace();
}
return returnValue;
}

Related

Http 416, Requested range not satisfiable

I'm using http client to get data:
public static String getHttpResponse(String url) {
//LOGGER.info("Download page context from URL " + url);
String httpClientResponse = null;
try {
URI uri = new URIBuilder(url).build();
HttpResponse response;
HttpHost target = new HttpHost(uri.getHost());
HttpGet request = new HttpGet(uri);
//request.setConfig(config);
request.addHeader(new BasicHeader("User-Agent", "Mozilla/5.0"));
request.addHeader(new BasicHeader("Content-Type", "text/html"));
request.addHeader("Accept-Ranges", "bytes=100-1500");
org.apache.http.client.HttpClient
client = HttpClients.custom().build();
response = client.execute(target, request);
//LOGGER.info("Status Line for URL {} is {}", uri.getHost() + File.separator + uri.getPath(), response.getStatusLine());
InputStream inputStream = response.getEntity().getContent();
if (inputStream == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
/*LOGGER.error("Non-success response while downloading image. Response {}", response.getStatusLine());
LOGGER.error("Error while download data from url {}", url);*/
} else {
httpClientResponse = IOUtils.toString(inputStream, CharEncoding.UTF_8);
}
} catch (Exception e) {
System.out.println("Error while download content from URL");
}
return httpClientResponse;
}
Also: Can we do this using Jsoup?
Thanks.
Replace:
request.addHeader("Accept-Ranges", "bytes=100-1500");
with:
request.addHeader("Range", "bytes=100-1500");
The Accept-Ranges header is part of server response, which indicates that the server accepts partial requests.
In your request you should use Range header, which indicates which part of document server should return.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range

Get the JSON response instead of text/html

authenticate_user method intended to create it to get the list of projects through the REST API in java:
#GET
#Path("/projects")
#Produces({MediaType.APPLICATION_JSON})
public boolean authenticate_user(String username, String password)
{
boolean status = false;
boolean isUser = isUserExists(username, password);
if (isUser)
{
HttpResponse response = clientConfig(username, password, "projects");
System.out.println("ProjectResponse >>>" + response);
HttpEntity entity = response.getEntity();
String content=null;
try
{
content = EntityUtils.toString(entity);
}
catch (ParseException | IOException e)
{
e.printStackTrace();
}
System.out.println("ResponseContent><><><"+content);
System.out.println("ContentMimeType: "+EntityUtils.getContentMimeType(entity));
if (response != null)
{
JSONArray getArray =new JSONArray();//Projects
status=true;
System.out.println("SuccessFully login");
}else
{
// TODO user is not validated
System.out.println("Error: Not Authenticated");
status = false;
}
} return status;
}
ClientConfiguration class:
public HttpResponse clientConfig(String username, String password, String prms)
{
try
{
HttpClient httpclient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://" + _HOST + "/" + prms);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("Type", "Basic Auth"));
nvps.add(new BasicNameValuePair("Username", username));
nvps.add(new BasicNameValuePair("Password", password));
httpget.setHeader("Authorization", "Basic " + new UrlEncodedFormEntity(nvps));
// Execute and get the response.
httpget.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpget, httpContext);
response.setHeader("Content-Type", "application/json");
if (response.getStatusLine().getStatusCode() != 200)
{
throw new IOException("Non-successful HTTP response: " + response.getStatusLine().getStatusCode() + ":"
+ response.getStatusLine().getReasonPhrase());
}
else if (response.getStatusLine().getStatusCode() == 200)
{
System.out.println("Response>>>" + response);
System.out.println("HTTPResponse: " + response.getStatusLine().getStatusCode() + ":"
+ response.getStatusLine().getReasonPhrase());
flag = true;
return response;
}
else
{
System.out.println("Status is not 200");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
And my output is html response instead of html response I need the JSON format, Its return me login page
HTTPResponse: 200:OK
<!DOCTYPE html>
<html lang="en">
................ </html>
ContentMimeType: text/html
SuccessFully login
Any one help me to find out the problem.
Try like this:
String json_string = EntityUtils.toString(response.getEntity());
JSONArray jsonArr = new JSONArray(json_string);
Thank you, Friends, Now I solved this issue with Jersey framework. And here is a solution of it.
String url = "http://support.sigmastream.com/issues.json";
String output = "";
String authString = username + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
try
{
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc).get(ClientResponse.class);
if (resp.getStatus() != 200)
{
throw new IOException(
"Non-successful HTTP response: " + resp.getStatus() + " : " + resp.getStatusInfo());
}
else
{
output = resp.getEntity(String.class);
System.out.println("response: " + output);
}
}
catch (IOException ie)
{
System.out.println(ie.getMessage());
}

How to get response from HttpPost

I want to get response from the httppost request. I get the network response like 200,405,404 but i don't get the value which is coming from server. I am trying a lot but i don't get response. Please help...
My code is below-
private void UploadPost() {
SharedPreferences sharedPreferences1 = getSharedPreferences("DATA", Context.MODE_PRIVATE);
String ID = sharedPreferences1.getString("id", "");
#SuppressWarnings("deprecation")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url.addOffer_url);
Log.e("uploadFile", "Source File Path " + picturePath);
File sourceFile1 = new File(picturePath);
if (!sourceFile1.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
imgUploadStatus = "Source File Does not exist";
}
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity();
File sourceFile = new File(picturePath);
MultipartEntity entity1 = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// Adding file data to http body
entity.addPart("retailer_id", new StringBody(ID));
entity.addPart("title", new StringBody(addoffertitle));
entity.addPart("description", new StringBody(addofferdesc));
entity.addPart("keyword", new StringBody(addofferkeyword));
entity.addPart("offer_id", new StringBody(OfferListing_Id));
// entity.addPart("payment_status",new StringBody(paymentStatus));
// if(!picturePath.equals(""))
entity.addPart("offer_image", new FileBody(sourceFile));
/* else
entity.addPart("old_pic",new StringBody(Image_Path));*/
httppost.setEntity(entity);
Log.d("httppost success", "httppost");
//Run a api for net conn check
try {
String responseString= new String();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity8 = response.getEntity();
if(entity8 !=null){
responseString = EntityUtils.toString(entity8, "UTF-8");
System.out.println("Response body: " + responseString);
}
statusCode = 200;
} catch (FileNotFoundException e) {
Log.e("log_tag1", "Error FileNotFoundException new service" + e.toString());
result = "FileNotFoundException";
} catch (SocketTimeoutException e) {
Log.e("log_tag2", "SocketTimeoutException new service " + e.toString());
result = "SocketTimeoutException";
} catch (Exception e) {
Log.e("log_tag3", "Error converting OtherException new service " + e.toString());
result = "OtherException";
}
if (statusCode == 200) {
// Server response
responseString = "success";
Log.e("complete success", "Response from server: " + responseString);
} else if (statusCode == 404) {
responseString = "page not found";
Log.e("complete page not found", "Response from server: " + responseString);
} else if (statusCode == 405) {
responseString = "no net";
Log.e("complete no net", "Response from server: " + responseString);
} else {
responseString = "other";
Log.e("complete other", "Response from server: " + responseString);
}
} catch (Exception e) {
responseString = e.toString();
responseString = "other";
Log.e("complete", "Response from server: " + responseString);
}
}
I want to response from the httppost.i get the network response but i don't get the value which is coming from server.I am trying a lot but i don't get response.Please help...
Try using EntityUtils instead of the BufferedReader. For instance, something like:
String responseString= new String();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity !=null){
responseString = EntityUtils.toString(entity, "UTF-8");
}
Look at the selected answer here - it shows how to get response body for a 400-HTTP response. You can also look at this example. If you are working with JSON payload, perhaps you might want to consider using Volley - here are some examples for PUT, POST, and GET requests using Volley
You can try this
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
Instead of
HttpEntity entity8 = response.getEntity();
if(entity8 !=null){
responseString = EntityUtils.toString(entity8, "UTF-8");
System.out.println("Response body: " + responseString);
}

Javax-RS - how to create a client to push data to a server?

I need to push data from a standalone client back to the server. This client already accesses the server to get information, parses it, executes what it has to do, but now I need it to push back some information.
I have tried doing this:
public class UpdateServer {
public void update(int resultSetRowCount) {
AgentConfiguration config = new AgentConfiguration();
config.init();
String agentId = AgentConfiguration.agent_id;
String serverIp = AgentConfiguration.server_ip;
String serverPort = AgentConfiguration.server_port;
Calendar cal = Calendar.getInstance();
StringBuilder timestamp = new StringBuilder();
timestamp.append(cal.get(Calendar.YEAR));
timestamp.append(String.format("%02d",cal.get(Calendar.MONTH) + 1));
timestamp.append(String.format("%02d",cal.get(Calendar.DAY_OF_MONTH)));
timestamp.append(String.format("%02d",cal.get(Calendar.HOUR_OF_DAY)));
timestamp.append(String.format("%02d",cal.get(Calendar.MINUTE)));
timestamp.append(String.format("%02d",cal.get(Calendar.SECOND)));
String date = timestamp.toString();
String uri = "http://" + serverIp + ":" + serverPort + "/hrm/alerts/" + agentId + "/" + date + "/" + resultSetRowCount;
System.out.println(uri);
try {
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
// Create new patchRequest with below mentioned URL
HttpPost postRequest = new HttpPost(uri);
// Add additional header to postRequest which accepts application/xml data
postRequest.addHeader("accept", "application/xml");
// Execute your request and catch response
HttpResponse response = httpClient.execute(postRequest);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm trying to access the server with the formatted uri using:
new UpdateServer().update(resultSetRowCount);
But I'm getting the following exception:
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 405
What am I missing here?
One of the causes of http error code 405 is when a payload is not passed to the POST method. Probably that is the case with your program.
You can use PostMethod instead of HttpPost and set the payload
Your code will look like
...
String uri = "http://" + serverIp + ":" + serverPort + "/hrm/alerts/" + agentId + "/" + date + "/" + resultSetRowCount;
System.out.println(uri);
try
{
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
PostMethod post = new PostMethod(uri);
RequestEntity requestEntity = new StringRequestEntity(payload, "application/xml", null/*charset default*/);
post.setRequestEntity(requestEntity);
int iResult = httpclient.executeMethod(post);
// get the status code using post.getStatusCode()
// you can get the response using post.getResponseBodyAsString()
// Check for HTTP response code: 200 = success
if (post.getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + post.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

How to build a http post request with the correct entity with Java and not using any library?

How should I build the entity to achieve this post request?
POST https://picasaweb.google.com/data/feed/api/user/userID/albumid/albumID/photoid/photoID
<entry xmlns='http://www.w3.org/2005/Atom'>
<content>great photo!</content>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/photos/2007#comment"/>
</entry>
It's from:
http://code.google.com/intl/zh-TW/apis/picasaweb/docs/2.0/developers_guide_protocol.html#AddComments
Could someone provide an example or any tips?
Many thanks.
UPDATE:
I added my code here:
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("GData-Version", "2"));
headers.add(new BasicHeader("Authorization", "GoogleLogin auth=" + mAuthToken));
EntityTemplate entity = new EntityTemplate(new ContentProducer() {
public void writeTo(OutputStream ostream) throws IOException {
Writer writer = new OutputStreamWriter(ostream, "UTF-8");
writer.write("\r\n");
writer.write("<entry xmlns='http://www.w3.org/2005/Atom'>");
writer.write("<content>" + comment + "</content>");
writer.write("<category scheme=\"http://schemas.google.com/g/2005#kind\"\r\n");
writer.write("term=\"http://schemas.google.com/photos/2007#comment\"/>");
writer.write("</entry>\r\n");
writer.flush();
}
});
Still no luck. Any idea?
It is a sample code using HttpClient.
I hope this piece of information will be of help to you.
// yourID
String userID = "";
String albumID = "";
String photoID = "";
HttpPost postRequest = new HttpPost(
"https://picasaweb.google.com/data/feed/api/user/" + userID
+ "/albumid/" + albumID + "/photoid/" + photoID);
postRequest.addHeader(new BasicHeader("GData-Version", "2.0"));
postRequest.addHeader(new BasicHeader("Authorization",
"GoogleLogin auth=" + mAuthToken));
String content =
"<entry xmlns='http://www.w3.org/2005/Atom'>"
+ "<content>" + comment + "</content>"
+ "<category scheme='http://schemas.google.com/g/2005#kind'"
+ " term='http://schemas.google.com/photos/2007#comment'/>"
+ "</entry>";
try {
StringEntity entity = new StringEntity(content);
entity.setContentType(new BasicHeader("Content-Type",
"application/atom+xml"));
postRequest.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(postRequest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use "GDataAPI" and "Guava-libraries".
PicasawebService myService
= new PicasawebService("exampleCo-exampleApp-1"); // just id
myService.setUserCredentials(
"liz#gmail.com", "mypassword"); // your mailaddress, password
// change "username", "albumid" and "photoid"
URL feedUrl = new URL(
"https://picasaweb.google.com/data/feed/api/"
+ "user/username/albumid/albumid/photoid/photoid");
CommentEntry myComment = new CommentEntry();
myComment.setContent(
new PlainTextConstruct("great photo!")); // there is comment
myService.insert(feedUrl, myComment);
Refere to following URL.
http://code.google.com/intl/ja/apis/picasaweb/docs/2.0/developers_guide_java.html
http://code.google.com/p/gdata-java-client/downloads (GDataAPI Download)
http://code.google.com/p/guava-libraries/ (Guava-libraries)
You can use HttpClient from apache httpcomponents to create http requests.
Find the tutorials here.

Categories

Resources