Microsoft graph search feature Java - java

I'm trying to use Microsoft Graph to make a file search. I use this entry point : https://graph.microsoft.com/beta/search/query
My application do not use a user account but a daemon with an application key (see auth method).
And i send a built object.
My java code is rather simple :
public static void main(String[] args) throws Exception{
try {
// Authentication result containing token
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
String token = result.accessToken();
SearchDocumentResponseModel documentQuery = fileGraphs.searchDocument(token, QUERYSTRING, 0, 25);
System.out.println("Find a document" + documentQuery.toString());
} catch(Exception ex){
throw ex;
}
}
private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ConfidentialClientApplication app = ConfidentialClientApplication.builder(
CONFIDENTIAL_CLIENT_ID,
ClientCredentialFactory.createFromSecret(CONFIDENTIAL_CLIENT_SECRET))
.authority(TENANT_SPECIFIC_AUTHORITY)
.build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(GRAPH_DEFAULT_SCOPE))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
The SearchDocumentResponseModel is just a set of POJO that build for me the object that i must send as a request body.
{
"requests":
[{
"entityTypes":["microsoft.graph.driveItem"],
"query":{"query_string":{"query":"any query"}},
"from":0,"size":25
}]
}
The method searchDocument is just here to build the object before i send it to the API
public SearchDocumentResponseModel searchDocument(String accessToken, String stringSearch, int from, int size) throws IOException {
SearchDocumentRequestModel searchRequest = new SearchDocumentRequestModel();
// set values here
...
URL url = new URL("https://graph.microsoft.com/beta/search/query");
return requestsBuilder.buildPostRequest(accessToken, searchRequest, url)
}
Now i want to send to server the Json and expect an answer :
public SearchDocumentResponseModel buildPostRequest(String accessToken, SearchDocumentRequestModel searchRequest, URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// write the input json in a string
String jsonInputString = new Gson().toJson(searchRequest);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
String httpResponseMessage = conn.getResponseMessage();
// reading the response
try(BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
String outputResponse = response.toString();
return new Gson().fromJson(outputResponse, SearchDocumentResponseModel.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I think i set the properties correctly. Is it coming from my code or from Microsoft Graph ? Thanks !

First of all, you should check if the access token is valid, you can send a request using postman.
If the token is valid, I think it should be the problem of your jsonInputString. The following code works fine.
URL url = new URL("https://graph.microsoft.com/beta/search/query");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "access_token" );
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json; utf-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String str = "";
str += "{";
str += " \"requests\": [";
str += " {";
str += " \"entityTypes\": [";
str += " \"microsoft.graph.driveItem\"";
str += " ],";
str += " \"query\": {";
str += " \"query_string\": {";
str += " \"query\": \"contoso\"";
str += " }";
str += " },";
str += " \"from\": 0,";
str += " \"size\": 25";
str += " }";
str += " ]";
str += "}";
OutputStream os = conn.getOutputStream();
byte[] input = str.getBytes("UTF-8");
os.write(input, 0, input.length);
System.out.println(conn.getResponseCode());
Update:
Query api doesn't support client credential flow.

Related

Post form data to server Api (Android)

I need to submit my registration form details to server api. I have tried one method by calling a function on button click.But nothing is geting posted in the server and I am also not getting any exception.Please help me.
Thanks in advance.
Below is the code .
I have called the function like this
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
// CALL GetText method to make post method call
GetText();
}
catch(Exception ex)
{
ex.printStackTrace();;
Toast.makeText(getActivity(),"URL Exception", Toast.LENGTH_LONG).show();
}
And below given is the function
public String GetText() throws UnsupportedEncodingException
{
HttpURLConnection connection = null;
// Get user defined values
Name = full_name.getText().toString();
Phonenumber = phone.getText().toString();
Email=email.getText().toString();
Password=password.getText().toString();
House = house.getText().toString();
Street = street.getText().toString();
Landmark = landmark.getText().toString();
// Create data variable for sent values to server
String data = URLEncoder.encode("name", "UTF-8")
+ "=" + URLEncoder.encode(Name, "UTF-8");
data += "&" + URLEncoder.encode("email", "UTF-8") + "="
+ URLEncoder.encode(Email, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode(Password, "UTF-8");
data += "&" + URLEncoder.encode("phone", "UTF-8")
+ "=" + URLEncoder.encode(Phonenumber, "UTF-8");
data += "&" + URLEncoder.encode("house", "UTF-8")
+ "=" + URLEncoder.encode(House, "UTF-8");
data += "&" + URLEncoder.encode("street", "UTF-8")
+ "=" + URLEncoder.encode(Street, "UTF-8");
data += "&" + URLEncoder.encode("areaname", "UTF-8")
+ "=" + URLEncoder.encode(Area, "UTF-8");
data += "&" + URLEncoder.encode("landmark", "UTF-8")
+ "=" + URLEncoder.encode(Landmark, "UTF-8");
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://application.easypani.com/app/customer/register");
// Send POST data request
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(data.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes(data);
wr.flush();
wr.close();
// Get the server response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
Use this instead
private class PostData extends AsyncTask < String, Void, Void > {
protected Void doInBackground(String...params) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://application.easypani.com/app/customer/register");
try {
// Add your data
String Name = params[0];
String Phonenumber = params[1];
String Email = params[2];
String Password = params[3];
String House = params[4];
String Street = params[5];
String Landmark = params[6];
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
nameValuePairs.add(new BasicNameValuePair("name", Name));
nameValuePairs.add(new BasicNameValuePair("email", Email));............................................................
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
}
And you use it like this
new PostData().execute(Name, PhoneNumber..and so on);

sending chinese text in post method in java

I need to send some Chinese and Korean text to a server using a post request in java. I have tried the following but it does not work.What I receive on server side are junk or '????'.
public static String HttpPostGeneric(String URLstr, String[] paramName, String[] paramVal)
{
try{
String parameters = null;
if ((paramName != null ) && (paramVal != null))
{
parameters = paramName[0] +"="+ paramVal[0];
URLEncoder.encode(parameters, "US-ASCII").replace("+", "%20");
for (int i = 1; i < paramName.length; i++)
{
parameters+= "&";
parameters += URLEncoder.encode(paramName[i], "US-ASCII").replace("+", "%20") + "=" + URLEncoder.encode(paramVal[i], "US-ASCII").replace("+", "%20");
//parameters += paramName[i] + "=" + paramVal[i];
}
}
//parameters = URLEncoder.encode(parameters, "US-ASCII");
byte[] postData = parameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL( URLstr );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setRequestProperty("charset", "US_ASCII");
conn.setRequestProperty("Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
//System.out.print(postData);
}
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
return line;
}
reader.close();
return line;
}catch(Exception e)
{
return e.getMessage();
}
}
Using UTF-8 encoding instead of US-ASCII also does not help.
What do I do?
Using UTF-8 encoding instead of US-ASCII is not just here.
//parameters = URLEncoder.encode(parameters, "US-ASCII");
byte[] postData = parameters.getBytes(StandardCharsets.UTF_8)
but all.
the below may be work.
URLEncoder.encode(parameters, "UTF-8").replace("+", "%20");
...
parameters += URLEncoder.encode(paramName[i], "UTF-8").replace("+", "%20") + "=" + URLEncoder.encode(paramVal[i], "UTF-8").replace("+", "%20");
...
conn.setRequestProperty("charset", "UTF-8");
...
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),Charsets.UTF-8));
Hope that helped

Mysql insert statement and passing parameters to PHP

I am trying to execute various statements/queries in my PHP file, depending on what variables are received (moreover, is there a way to send variables and choose what kind of query I want to do, as opposed to making one query for each set of variables received? This is my first time writing in PHP so please forgive the possible stupid question).
In this case its a Username, Password, and UserID. I'd like an insert to occur when these 3 variables are received. However, I keep on receiving an error: java.net.ProtocolException: method does not support a request body: GET (this is when conn.setDoOutput isset to true). If I have it set to false, I get a IO URL error which states my URL cannot be found. What am I doing wrong? Below are both my php script and the java code used for GET requests.
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
Since this PHP script does an INSERT statement, it's strongly recommended that you use POST parameters.
Java code:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = "&" + URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP script:
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['un']) && isset($_POST['pw']) && isset($_POST['uid'])){
$uname = mysql_real_escape_string($_POST['un']);
$pass = mysql_real_escape_string($_POST['pw']);
$uid = intval($_POST['uid']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
As an aside, for a GET request, you just append the parameters to the end of the url when you create the URL object.
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
String urlString = "phpfilelocation.php" + "?" + data;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.connect();
//remove:
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//wr.write(data);
//wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
PHP :
mysql_query("INSERT INTO Users(id, UserName, Password)
VALUES ('$uid', '$uname', '$pass')");
JAVA :
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String unameDB="username";
String passDB="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,unameDB,passDB);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `Users`(ID,UserName,Password) VALUE ('"+uid+"','"+uname+"','"+pass+"')");

Response :java.net.SocketException: Unexpected end of file from server Java

I got this error from my program when i am call a URL from URLConnector.. the URL is
http://192.168.2.107/cgi-bin/mediaFileFind.cgi?action=findFile&object=27544704&condition.Channel=0&conditon.Dir[0]="/mnt/sd"&condition.StartTime=2014-8-1 00:00:00&condition.EndTime=2014-8-31 23:59:59
but when i capture HTTP using wire-shark then wire-shark the URl is loss
wire-shark capture only
http://192.168.2.107/cgi-bin/mediaFileFind.cgi?action=findFile&object=27544704&condition.Channel=0&conditon.Dir[0]="/mnt/sd"&condition.StartTime=2014-8-1 00:00:00
only this URL
my Java program is
public String intilizeObject(String IP, String user, String pass, String objectID, String dir, String startTime, String endTime) {
String result = "";
try {
String URL = "http://" + IP + "/cgi-bin/mediaFileFind.cgi?action=findFile&object=" + objectID + "&condition.Channel=0&conditon.Dir[0]=\"" + dir + "\"&condition.StartTime=" + startTime + "&condition.EndTime=" + endTime;
String authString = user + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL url = new URL(URL);
System.out.println(url);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
result = sb.toString();
} catch (Exception e) {
result = e.toString();
}
return result;
}

HTTPS login? Java

I am trying to write a segment of code that will attempt to login to twitter to check if user name is correct and then return if it is true or false. It is not working due to the fact that if I put in the correct user name and pass that I still get the sign in page.
public class httpConnect {
//Variables
public Boolean correctCredentials(String site, String user, String pass) {
String data = connect(site, user, pass);
char[] charArray = data.toCharArray();
try {
File log = new File("C:\\Users\\________\\Desktop" + "\\" + "log.txt");
if (log.exists()) {
Scanner scan = new Scanner(log);
while (scan.hasNextLine()) {
String temp = scan.nextLine();
temp = charArray.toString() + (char) 10 + (char) 10 + (char) 10 + temp;
charArray = temp.toCharArray();
}
}
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Users\\________\\Desktop" + "\\" + "log.txt", true)); //bufferedWriter for speed
out.append((char) 10);
for (int x = 0; x < charArray.length; x++) {
out.append(charArray[x]);
}
out.flush();
out.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e + "\nSorry, could not write File"); //gives error if path does not exist
}
return false;
}
public String connect(String site, String user, String pass) {
StringBuilder response = new StringBuilder();
;
try {
String encodedUser = URLEncoder.encode(user, "UTF-8");
String encodedPass = URLEncoder.encode(pass, "UTF-8");
/*
* commit - LOGIN_ACTION_NAME
* session[username_or_email] - LOGIN_USER_NAME_PARAMETER_NAME
* session[password] - LOGIN_PASSWORD_PARAMETER_NAME
*/
String content = "login=" + "commit" + " amp;amp;"
+ "session[username_or_email]" + "=" + encodedUser + "amp;amp;"
+ "session[password]" + "=" + encodedPass;
HttpsURLConnection urlConnect = (HttpsURLConnection) (new URL(site).openConnection());
urlConnect.setDoInput(true);
urlConnect.setDoOutput(true);
urlConnect.setRequestProperty("Content-Type", "text/html; charset=utf-8");
urlConnect.setRequestMethod("POST");
DataOutputStream dataOutputStream = new DataOutputStream(urlConnect.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
BufferedReader buf = new BufferedReader(new InputStreamReader(urlConnect.getInputStream()));
String responseLine = "";
while ((responseLine = buf.readLine()) != null) {
response.append(responseLine);
}
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
}
So basically what I am going to do is attempt login and then scan page to see if title says "Twitter \ Home" and if it does then I know I logged in correctly. I have not gotten that far, but when I browse it myself it does not work.
Btw I don't want to use Twitter4j because it refuses to return a Boolean.
It also may be that I do not have the right page to attempt to log into. How would I find it? What would it be for twitter?
Have you had a look at using the official Twitter API (http://dev.twitter.com/doc) to do this?
Looking at your code suggests that you're mimicking the browser's authentication requests, but this probably misses out some information such as cookies, request tokens and whatever else they might use in their login page.

Categories