Upload a file to Sharepoint online using REST API in JAVA - java

I am new to sharepoint rest API and am facing some issue while upload a file(image, document, pdf etc.,) to sharepoint online. Thanks in advance.
The below is our requirement.
User will upload the document which are stored at a particular location in application server.
A cron job will be running on application server and push the documents to share point online depend upon business needs.
To achieve it, we follow the below steps.
Authentication done via AZURE access token (We have used client credential flow to get access token from AZURE AD and able to communicate with sahrepoint online with access token.)
We have consumed the sharepoint online REST API to do file operation like upload, download etc,. using java code.
Here we are able to download the file from sharepoint online but when we upload the file, we are getting response as "BAD REQUEST" and status code is "400"
Sharepoint online rest API to create a file:
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)
method: POST
body: "Contents of file"
Headers:
Authorization: "Bearer " + accessToken
X-RequestDigest: form digest value
content-length:length of post body
My Java code :
//Create HttpURLConnection
String token ="js#1ikssj......RDS2" // This is just sample
String request = "Create a File with raw string !!!";
java.net.URL url = new java.net.URL("http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)");
java.net.URLConnection connection = url.openConnection();
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connection;
//Set Header
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Authorization", "Bearer " +token);
httpConn.setRequestProperty ("Accept", "application/json;odata=verbose");
httpConn.setRequestProperty("binaryStringRequestBody", "true");
//Send Request
java.io.DataOutputStream wr = new java.io.DataOutputStream(httpConn.getOutputStream ());
wr.writeBytes(request);
wr.flush();
wr.close();
//Read the response.
String StatusMessage = "HTTP ResponseCode: " + httpConn.getResponseCode() + " "+ httpConn.getResponseMessage();
Response : 400 - BAD REQUEST.

You can take a look of this project where you can find a working implementation of uploading files, creating folders, managing folder user permissions and more. It's a very easy to use API with most common operations of the rest API
https://github.com/kikovalle/PLGSharepointRestAPI-java

Related

Login to an application URL and POST Data using Java

I want to login to an authentication based application URL use those cookies/token to POST the json data to a mapping with java.
Login URL and POST URL are different and predefined in the application. (I can't change the URLs)
I tested using Postman and I can POST the data using the JSESSIONID and CSRF token from login Url but I have to do it using microservices.
I am new to java so I am not sure how to implement it. Can you please help with a sample code
What you need is Java Http client. There are several well known 3d party Http clients out there. Basically with each one you will need to replicate the same Http requests that you sent with your postman. For each request from postman (you are talking about 2 API end-points here: Login URL and some post method for exchange of the info using the token you received in from your login call) you can see the headers that you sent and you will need to send the same headers with your Http clients of your choice. Here are some recommended Http clients:
Apache Http Client. See links: HttpClient Overview and Apache HttpComponents - This is one of the most reliable and popular Http clients
OK Http Client. See links OkHttpClient, OkHttp Maven repository
Http client from MgntUtils library - This one is not well known client, and it does not provide all the width of functionality as the other ones, but its advantage that it is very simple in usage and it definitely would be good enough for what you need to acompllish. Disclaimer - MgntUtils library is written and maintained by me. Here is the Javadoc for HttpClient class. The MgntUtils library can be obtained as Maven artifacts and from Github (including source code and Javadoc). Here is an example of code. Lets say you called the Login API and obtained the token. So a call to your post method with MgntUtils HttpClient may look as something like this:
private static void bizServiceAdminAppTest() {
TextUtils.setRelevantPackage("com.mgnt.stam.");
HttpClient client = new HttpClient();
try {
client.setContentType("application/json; charset=UTF-8");
client.setRequestHeader("Accept", "*/*");
client.setRequestHeader("Authorization", "Bearer <token value>");
client.setRequestHeader("cookie", "<My cookie value>");
client.setConnectionUrl("http://my-server-address/some/path/");
String result = client.sendHttpRequest(HttpClient.HttpMethod.POST, "{\"some key\": 317809,\n" +
" \"key for list of values\": [\n" +
" \t2154377, 564\n" +
" ]\n" +
"}");
System.out.println(client.getLastResponseCode() + " " + client.getLastResponseMessage() + "\n" + result);
} catch (IOException ioe) {
System.out.println(client.getLastResponseCode() + " " + client.getLastResponseMessage());
System.out.println(TextUtils.getStacktrace(ioe));
}
}

SonarQube Java Web API

I want to create QualityGates with the Web API in java.
String auth = username + ":" + password;
String authEncoded = Base64.getEncoder().encodeToString(auth.getBytes());
URL sonar = new URL("http://xxx.xxx.xxx.xx:9000/api/qualitygates/create");
HttpURLConnection conn = (HttpURLConnection) sonar.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authEncoded);
I dont seem to find anything in the topic of POST to web API.
In the Code i basically try to connect to the API with the Admin user authentication.
The Problem is, it doesnt matter what i do i always get ResponseCode 400. I know that it needs a name as a Property to create the QualityGate but that also doesnt seem to work.
My Question:
What do i need to do to use the POST method on web API's.
Best regards!
This isn't really a SonarQube question. It's a question about how to use POST apis. The API is returning a 400 error because you're not sending any data in the POST, and a POST expects data.
Read the answer to the following thread for hints on how to send data in a POST: Java - sending HTTP parameters via POST method easily .

CA service DESK REST api using JAVA

Our infra team set up the ca service desk in machine and share the details. I need to make rest call to create the incident from java program. And here i want to use basic authentication by providing the access key. For this I tried to make the end point url to get the access key and after that to create incident as shown below.
http://Host:port/caisd-rest/rest_access
http://CAdeskHost:port/caisd-rest/in
String endpoint = "http://host:port/caisd-rest/rest_access";
HttpClient client = new HttpClient();
String encodedCredentials = new String(Base64.encodeBase64(("username" + ":" + "password").getBytes()));
PostMethod post = new PostMethod(endpoint);
post.addRequestHeader("Accept", "application/xml");
post.addRequestHeader("Content-Type", "application/xml; charset=UTF-8");
post.addRequestHeader("Authorization", "Basic " + encodedCredentials);
post.setRequestBody("<rest_access/>");
try {
System.out.println("Execute Basic Authentication request on " + endpoint);
// Execute request
int result = client.executeMethod(post);
But when I try to execute the above code, getting the 404 error
"The requested resource (/caisd-rest/rest_access) is not available".
Can any one please help me how to find the REST URL for ca service desk whether it is common url for all like /caisd-rest or it is different. Here my infra team just installed the CA service desk. So do we need to do any other steps to provide rest access?
Check in CA Technologies Website, it should be http://<host>:<REST port>/caisd-rest
I had the same issue, problem was that REST wasn't deployed properly, reconfiguring REST Service using this doc: REST API reconfiguration resolved the problem.
I folowed these steps:
Check for existence of NX_ROOT/bopcfg/www/CATALINA_BASE_REST/webapps/caisd-rest. If this directory does NOT exist, that's a very good indication that the REST deploy did not work properly.
Check for the errors in NX_ROOT/log/jrest.log file.
Try fix errors and redeploy REST Service using cmd:
pdm_rest_util -undeploy
pdm_rest_util -deploy

Getting 401 when signing HTTP message with signpost

I am integrating my web app with AppDirect,
for this I created a java rs API using jersey.
When I subscribe to an event, I get a map containing the oauth values (key and secret) to sign my request and an event url to which I issue a sign fetch to.
I am getting those values (oauth and eventurl) as expected.
Now when I try to issue a signed fetch using the library signpost, I use the following code:
OAuthConsumer consumer = new DefaultOAuthConsumer(consumer_key, secret);
// create an HTTP request to a protected resource
URL url = new URL(eventUrl);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
// sign the request
consumer.sign(request);
// send the request
request.connect();
I get this error message:
getResponseMessage: Unauthorized
getresponsecode: 401
I also tried with the following test values:
url = "https://www.appdirect.com/api/integration/v1/events/dummyOrder";
dummyKey = "Dummy";
dummySecret = "secret";
But I got the same result.
Please how can I fix it?
I also tried and adding this:
request.setRequestMethod("GET");
request.setRequestProperty("Authorization", "OAuth");
request.setRequestProperty("Host", "...");
request.setRequestProperty("Content-Type", "application/xml");
request.setRequestProperty("oauth_nonce", oauth_nonce);
request.setRequestProperty("oauth_signature", oauth_signature);
request.setRequestProperty("oauth_signature_method", oauth_signature_method);
request.setRequestProperty("oauth_timestamp", oauth_timestamp);
request.setRequestProperty("oauth_version", oauth_version);
also tried with key:secret in the Authorization property
Here is a behavior of this service when testing via Postman Chrome extension.
If you are using OAuth provider, so you need to get valid api-key for AppDirect and secret.
BTW second screenshot shows you don't need to send an OAuth token to appdirect to https://www.appdirect.com/api/integration/v1/events/dummyOrder, because it authorizes any url.
So, according to your notes, you have to add proper(secret and key) and then AppDirect OAuth server will return you a valid token which you will use when addressing AppDirect's repositories. Or you may send key-secret with each request.

How do I use OAuth with Imgur?

So I am trying to get information of various images, for which I will use the Imgur API through Java.
I have found a library: https://github.com/fernandezpablo85/scribe-java,
but when trying the ImgUrTest.java # https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/ImgUrExample.java, I get the following stacktrace:
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'OAuth Verification Failed: The consumer_key "<Client-ID>" token "" combination does not exist or is not enabled.'
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at ImgUrExample.main(ImgUrExample.java:31)
where <Client-ID> is my client id, as found on ImgUr's page.
I have checked that my Client Id and Client Secret are correct, I have tried making multiple apps on the ImgUr site, none of which work.
Edit: This code works:
URL imgURL = new URL(YOUR_REQUEST_URL);
HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection();
conn.setRequestMethod("GET");
if (accessToken != null) {
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
} else {
conn.setRequestProperty("Authorization", "Client-ID " + CLIENT_ID);
}
BufferedReader bin = null;
bin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
First, the example is using Imgur API v2 which is old and unsupported. You should be using API v3.
Also note that:
For public read-only and anonymous resources, such as getting image
info, looking up user comments, etc. all you need to do is send an
authorization header with your client_id in your requests.
from docs at https://api.imgur.com/oauth2 -- so you don't really need OAuth for what you're doing.
There is some example Imgur API code that might help you, listed at https://api.imgur.com/ -- the Android example might be more relevant to you, since it uses Java, but unsurprisingly it comes with all the overhead of an Android project, compared with a plain Java application.

Categories

Resources