I want to get a list with all files and dirs in a dir located on a sharepoint
I do not have experience with REST api and I can not find this specific problem solved on google
I have the current code:
HttpURLConnection sharepoint = new LoginManager().login();
String siteURL = "https://confidential.sharepoint.com/something/"; //here <siteURL_path> is '/teams/SPdev/AlertsCount'
String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('TheFolder')";
//Send Request
InputStream in = sharepoint.getInputStream();
//Read the response.
String responseStr = "";
if (sharepoint.getResponseCode() == 302)
{
responseStr = "Folder read. ResponseCode: " + sharepoint.getResponseCode();
}
else
{
responseStr += "Error while reading folder, ResponseCode: " + sharepoint.getResponseCode() + " " + sharepoint.getResponseMessage();
}
System.out.println(responseStr);
Where LoginManager is something I did folowing this:
https://social.technet.microsoft.com/Forums/office/en-US/4c8d3696-1d41-44e3-897c-ac3c0b44f66a/share-point-online-authentication-using-java?forum=sharepointsearch
Related
I am new to OKTA.
Using the below code to get the access token.. but getting 401 unauthorized error in this line
inputBuff = new BufferedReader(new
InputStreamReader(httpsClient.getInputStream()));
String oktaURL = "https://xxx.oktapreview.com/oauth2/default/v1/token";
String urlParameters = “client_id=” + clientId+“grant_type=authorization_code&redirect_uri=”+“http://:8192/app”+"&code="+oktaCode;
URL url1 = new URL(oktaURL);
StringBuffer response = null;
String output1;
log.info("The url to get the access token:"+url1.toString());
if (url1.getProtocol() != null && url1.getProtocol().startsWith("https")){
//String encodedData = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes("UTF-8"));
//String authorizationHeaderString = "Authorization: Basic " + encodedData;
httpsClient = (HttpsURLConnection) url1.openConnection();
httpsClient.setRequestMethod("POST");
httpsClient.setRequestProperty("Accept","application/json");
httpsClient.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()));
httpsClient.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpsClient.setInstanceFollowRedirects(false);
log.info ("Send the POST request");
// Send post request
httpsClient.setDoOutput(true);
try (DataOutputStream opStream = new DataOutputStream(httpsClient.getOutputStream())) {
opStream.writeBytes(urlParameters);
opStream.flush();
}
inputBuff = new BufferedReader(new InputStreamReader(httpsClient.getInputStream())); // throwing 401 here.
log.info("Read from the input stream");
response = new StringBuffer();
while ((output1 = inputBuff.readLine()) != null) {
response.append(output1);
}
}
if (response != null) {
String theString = response.toString();
log.trace("Info:"+theString);
}
I could navigate to OKTA server's login page via /authorize URL and then authentication is successful and coming back to my application. Now trying to get access token. Please help how to solve this in java.
I just checked the okta log, it says the below right above the authenticate success log.
You forgot to put & after your actual client_id, so your string should look like
String urlParameters =
"client_id=" + clientId +
"&grant_type=authorization_code" +
"&redirect_uri=" + "http://:8192/app" +
"&code=" + oktaCode;
Solve the issue, there were 2 issues.
Removed client_id from urlParameters as its given in Authorization header
Removed default from /token endpoint as its not give in my /authorize endpoint.
I am trying to use JAVA NIO to transfer a file from host A to client B without having to download the file locally and then giving the client B a link to download the file.
I am running a spark Apache framework and using maven project.
I mapped the request http://localhost:8080/download/hello in Spark using :
get("/download/:id",RequestHandler::downloadHandler);
Inside of the function is the code that downloads the file from :
"https://download.springsource.com/release/STS/3.8.1.RELEASE/dist/e4.6/spring-tool-suite-3.8.1.RELEASE-e4.6-linux-gtk-x86_64.tar.gz"
try {
URL url = new URL("https://download.springsource.com/release/STS/3.8.1.RELEASE/dist/e4.6/spring-tool-suite-3.8.1.RELEASE-e4.6-linux-gtk-x86_64.tar.gz");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int respCode = +httpURLConnection.getResponseCode();
System.out.println("response code : "+respCode);
if (respCode == HttpURLConnection.HTTP_OK){
String fileName = "";
String disposition = httpURLConnection.getHeaderField("Content-Disposition");
String contentType = httpURLConnection.getContentType();
int contentLength = httpURLConnection.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = url.toString().substring(url.toString().lastIndexOf("/") + 1,
url.toString().length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
httpURLConnection.disconnect();
System.out.println("other stuff : ");
System.out.println(url.getHost());
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
FileChannel fileChannel = fileOutputStream.getChannel();
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
readableByteChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
I fetch the filename and file size using httpURLConnection and then processed to download the file. what I am trying to do is, instead of downloading the file locally using fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE) transfer the file directly to the client.
I did some research and I think it is possible with using Socketchannels but I didn't understand how it is supposed to work.
I also read this article
https://examples.javacodegeeks.com/core-java/nio/java-nio-large-file-transfer-tutorial/
and tried to understand the class Reciever, but it is still not clear to me how.
I would appreciate some guidance. Thank you
how to send file with http request in java ?
i see question
Send image file using java HTTP POST connections
and
Upload files from Java client to a HTTP server
but them are too old question and not work any more .
A good example is given in Multi part File Upload example of Apache HttpClient
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup
The part that actually posts the file is
String targetURL = cmbURL.getSelectedItem().toString();
// add the URL to the combo model if it's not already there
if (!targetURL
.equals(
cmbURLModel.getElementAt(
cmbURL.getSelectedIndex()))) {
cmbURLModel.addElement(targetURL);
}
PostMethod filePost = new PostMethod(targetURL);
filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
cbxExpectHeader.isSelected());
try {
appendMessage("Uploading " + targetFile.getName() + " to " + targetURL);
Part[] parts = {
new FilePart(targetFile.getName(), targetFile)
};
filePost.setRequestEntity(
new MultipartRequestEntity(parts, filePost.getParams())
);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().
getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
appendMessage(
"Upload complete, response=" + filePost.getResponseBodyAsString()
);
} else {
appendMessage(
"Upload failed, response=" + HttpStatus.getStatusText(status)
);
}
} catch (Exception ex) {
appendMessage("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage());
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
Hope it is of some help to you.
I have a question about URI and URL
when i pass a url is work good but result is worst need help!!
as my code look like this.
import java.io.*;
import java.net.*;
import java.net.URL;
public class isms {
public static void main(String[] args) throws Exception {
try {
String user = new String ("boo");
String pass = new String ("boo");
String dstno = new String("60164038811"); //You are going compose a message to this destination number.
String msg = new String("你的哈达哈达!"); //Your message over here
int type = 2; //for unicode change to 2, normal will the 1.
String sendid = new String("isms"); //Malaysia does not support sender id yet.
// Send data
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass
+ "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
URL url = new URL(myUrl.toASCIIString());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Print the response output...
System.out.println(line);
}
rd.close();
System.out.println(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
the output in web is different..
on my java output is
你的哈达哈达!
but on my the site is
ÄãµÄ¹þ´ï¹þ´ï!
Help!!
String user = new String ("boo");
You don't need to (and shouldn't) do new String in Java—String user = "boo"; is fine.
String msg = new String("你的哈达哈达!");
Writing non-ASCII characters in your source means that you have to get the -encoding flag to javac to match the encoding you have saved your text files with. It is possible you have saved the .java file as UTF-8 but not configured your build environment to use UTF-8 at compile time.
If you are not sure that you've got this right, you can use ASCII-safe \u escapes in the meantime:
String msg = "\u4F60\u7684\u54C8\u8FBE\u54C8\u8FBE!"; // 你的哈达哈达!
Finally:
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass
+ "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
When you're putting a URI together you should URL-escape each of the parameters you include in the string. Otherwise any & or other invalid character in the value will break the query. This also allows you to choose what charset is used to create the query string.
String enc = "UTF-8";
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?" +
"un=" + URLEncoder.encode(user, enc) +
"&pwd=" + URLEncoder.encode(pass, enc) +
"&dstno=" + URLEncoder.encode(dstno, enc) +
"&msg=" + URLEncoder.encode(msg, enc) +
"&type=" + URLEncoder.encode(Integer.toString(type), enc) +
"&sendid=" + URLEncoder.encode(sendid, enc)
);
What the right value for enc is depends on the service you are connecting to, but UTF-8 is a good guess.
New to java, GWT and interacting with APIs. I have what I hope is a simple question.
I have successfully interacted with a REST API using the following curl command:
curl -d "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=xxxxxxxxxxx&INPUT_DATA=<?xml version=%221.0%22 encoding=%22utf-8%22?><Operation><Details><requester>Me</requester><subject>Test</subject><description>Testing curl input</description></Details></Operation>" http://xx.xx.xx.xx/sdpapi/request/
Now, from a tutorial, I have the following code that I am hoping will post a request to the remote server just like the curl command above.
What I am trying to figure out (with no love from google) is how I pass the OPERATION_NAME, TECHNICIAN_KEY and INPUT_DATA parameters in when I am sending the URL. Any suggestions, tutorials, etc. will be appreciated.
The following is from my server side implementation interface:
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
//dividing url into host: http://some.server
//path: a/path/in/it
//and parameters: this=that&those=others
int hostStart= serviceUrl.indexOf("//");
int pathStart= serviceUrl.substring(hostStart + 2).indexOf("/");
int parameterStart= serviceUrl.substring(hostStart + 2 + pathStart).indexOf("?");
final String serverHost= serviceUrl.substring(0, hostStart + pathStart + 2);
final String serverPath= serviceUrl.substring(hostStart + 3,
hostStart + pathStart + 2 + parameterStart);
final String serverParameters= serviceUrl.substring(hostStart + pathStart + 3 + parameterStart);
final URL url = new URL(serverHost);
final URLConnection connection= url.openConnection();
connection.setDoOutput(true);
final OutputStreamWriter out= new OutputStreamWriter(connection.getOutputStream());
final BufferedReader in= new BufferedReader(new InputStreamReader(
connection.getInputStream()));
out.write("POST " + serverPath + "\r\n");
out.write("Host: " + serverHost + "\r\n");
out.write("Accept-Encoding: identity\r\n");
out.write("Connection: close\r\n");
out.write("Content-Type: application/x-www-form-urlencoded\r\n");
out.write("Content-Length: " + serverParameters.length() + "\r\n\r\n" +
serverParameters + "\r\n");
String result = "";
String inputLine;
while ((inputLine=in.readLine()) != null) {
result+= inputLine;
}
in.close();
out.close();
return result;
} catch (final Exception e) {
throw new HelpDeskTestException();
}
Consider using this library: Apache HttpClient. Here is an example of making a POST request with it.