Flowgear Workflow Call using JAVA Post API - flowgear

Please help how to call flowgear workflow using JAVA POST API.
My flowgear end point is 6.somesubdomain.mydomain(This end point is valid?).I used this code to call flowgear workflow but it is not work my end point is not call(please check my end point is valid).
URL myURL = new URL("https://6.somesubdomain.mydomain.flowgear.io/test/");
HttpURLConnection con = (HttpURLConnection)myURL.openConnection();
String userCredentials = "email:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(somejsondata.toString());
osw.flush();
osw.close();
Please give me response.
Thanks.

Related

How to get microsoft account profile photo after login with application in mvc

With the help of claimprincipal, I'm able to get the details of signedin user as below but its not giving any pic related information as google does:
https://apis.live.net/v5.0/{USER_ID}/picture?type=large
which says The URL contains the path '{user_id}', which isn't supported.
Even tried
https://graph.microsoft.com/v1.0/me/photo/$value
which is asking for access token, but I am not sure what have to be passed
string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
Wanted an image which was added in any outlook account
For Image to show.. We have to use beared token and have to convert the image into memory stream and then have to used it.. I have done it in below ways. Hope this help ...
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);
var Token = jsonContent.AccessToken;
var TokenType = jsonContent.TokenType;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
if (response1.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}
Is there any reason you are using the live.net apis? Instead of the Microsoft Graph APIs? Microsoft Graph APIs are the future for all user data within Microsoft 365 consumer and commercial accounts.
You can get the Users photo very easily as described here https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
GET /me/photo/$value
As you are using ASP.NET MVC, there is an SDK you can use that makes this very easy too.
https://learn.microsoft.com/en-us/graph/sdks/sdks-overview?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

RestSharp Returning Unauthorized

I am having an issue and think I may be missing something with RestSharp.
I am authorizing and getting back a cookie just fine... see below. But then when I call to get the data it returns unauthorized. It works just fine in Postman but not in the code below. I am using a console app and I have tried to send the cookie via AddHeader, AddCookie, and just as a parameter. The responseLogin does contain the correct cookie. Any help would be great.
Dim clientLogin = New RestClient("http://[URI to Authorize]............")
Dim requestLogin = New RestRequest(Method.POST)
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody)
Dim responseLogin As IRestResponse = clientLogin.Execute(requestLogin)
Dim client = New RestClient("http://[URI to get data]............")
Dim request = New RestRequest(Method.GET)
request.AddHeader("Cookie", responseLogin.Cookies(0).Value.ToString)
request.AddHeader("Accept", "application/json")
Dim response As IRestResponse = client.Execute(request)
The Cookie header needs to contain the name and value for the cookie, e.g.
Dim authCookie = responseLogin.Cookies(0) ' Probably should find by name
request.AddHeader("Cookie", String.Format("{0}={1}", authCookie.Name, authCookie.Value))
However, the documentation (I've never used RestSharp personally) says that RestSharp has automatic support for cookies, so if you reuse the RestClient instance and set the CookieContainer you shouldn't need to do anything to handle the cookies manually (unless you want to, which in some cases may be preferable).
Dim client = New RestClient(New Uri("[Base URI...]"))
client.CookieContainer = New System.Net.CookieContainer()
Dim requestLogin = New RestRequest("[login page path]", Method.POST)
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody)
Dim responseLogin As IRestResponse = client.Execute(requestLogin)
Dim request = New RestRequest("[data api path", Method.GET)
request.AddHeader("Accept", "application/json")
Dim response As IRestResponse = client.Execute(request)
You could probably just reuse the cookie container with different RestClient instances instead of reusing the client.
I had the same issue on RestClient .NET framework 4.5.2 version.
It turns out you have to implement the IAuthenticator interface.
public class MyAuth : IAuthenticator
{
readonly string _password;
readonly string _passwordKey;
readonly string _username;
readonly string _usernameKey;
public MyAuth(string usernameKey, string username, string passwordKey, string password)
{
_usernameKey = usernameKey;
_username = username;
_passwordKey = passwordKey;
_password = password;
}
public void Authenticate(IRestClient client, IRestRequest request)
=> request
.AddCookie(_usernameKey, _username)
.AddCookie(_passwordKey, _password);
//.AddParameter(_usernameKey, _username)
//.AddParameter(_passwordKey, _password);
}
I did this and my request worked.

Shopify OAuth step 2 issue

When we try to post a request for step 2 of the authentication process, we get an http 400 error when sending request to https://hamill-murazik-and-johnston6698.myshopify.com/admin/oauth/access_token
We are able to get past step 1 and we get the temp code. But when we try to post the client_id, client_secret and code, we get back the http 400 error.
Code is shown below
public static void runTest() {
// TODO Auto-generated method stub
try{
URL url = new URL("https://hamill-murazik-and-johnston6698.myshopify.com/admin/oauth/access_token");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
String urlParameters = URLEncoder.encode("client_id", "UTF-8") + "=" + URLEncoder.encode("<CLIENT_ID", "UTF-8");
urlParameters += "&" + URLEncoder.encode("client_secret", "UTF-8") + "=" + URLEncoder.encode("<CLIENT_SECRET", "UTF-8");
urlParameters += "&" + URLEncoder.encode("code", "UTF-8") + "=" + URLEncoder.encode("15f01c0d8b235ffb63234c1c48822432", "UTF-8");
/*connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Length", Integer.toString(102454));
connection.setRequestProperty("Content-Type", "text/plain");*/
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
I'd suggest you use a real HTTP Client library such as the Apache HttpClient library. There is a good chance you are missing something in your request or encoding something incorrectly.
The library wil provide a simpler interface to work with as well, so you can just pass in things like key-value parameters for your HTTP params and it'll just work.
Also, it appears that you are appending your authorize request into your URL parameters. You need to make a POST request for that request. In your current implementation you'd have to send that in the Body, which can be awkward in plain Java.
I highly suggest using the HttpClient library, and letting us know if that helped you out.

Setting RequestHeaders for Get REST API in Visual Basic

I have located some sample source code in visual basic to call a REST API. However, I need to modify the code by adding two request headers.
' Create the web request
request = DirectCast(WebRequest.Create(sURI), HttpWebRequest)
'Update request headers with request pairs Header1/"header1 value" and header2/"header2 value"
??? HttpWebRequest.headers.Add ????
' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
reader = New StreamReader(response.GetResponseStream())
Any help would be appreciated. Thanks!
Many of the normal headers are "built-in," like so:
HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
Alternatively, you should be able to set any header you like with:
HttpWebRequest.Headers("Header1") = "Header1 value"
And another method in line with your original code:
HttpWebRequest.Headers.Add("Header1", "Header1 value")
You could consider using System.Net.WebClient.
Here is some code in C#
using (System.Net.WebClient client = new System.Net.WebClient())
{
string userInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("user:password"));
client.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + userInfo;
client.DownloadString(url)
}

IOException when making HttpWebRequest to local ASHX file

Greetings, all. Here is my situation. I am attempting to make an HttpWebRequest to a local handler file and I keep getting the following exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Now, I'm using a local handler file because I am writing some integration code for a third party that the site will be using. Until I have a test environment available for me to make requests to, I'm basically mocking the process with a local handler file. Here is the relevant code. Thanks.
WebRequest code (subRequest variable is object passed to the method executing this code):
XmlSerializer serializer;
XmlDocument xmlDoc = null;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.KeepAlive = true;
webRequest.Accept = "*/*";
serializer = new XmlSerializer(subRequest.GetType());
XmlWriter writer = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8);
serializer.Serialize(writer, subRequest);
writer.Close();
xmlDoc = new XmlDocument();
xmlDoc.Load(XmlReader.Create(webRequest.GetResponse().GetResponseStream()));
The "requestUrl" is defined as "http://localhost:2718/Handlers/MyHandler.ashx". I can hit the handler file just fine and have stepped through the code. All it does is assemble an XML response as a string and writes it out to the Response object:
context.Response.ContentType = "text/xml";
string newSubscriptionId = Utils.GetUniqueKey();
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
// Assemble XML string here
context.Response.Write(sb.ToString());
As far as I can tell, this is all working just fine. But when my code hits the last line of the WebRequest chunk:
xmlDoc.Load(XmlReader.Create(webRequest.GetResponse().GetResponseStream()));
Is when the exception is thrown. Any ideas? Thanks in advance.
James
First, if you don't intend to reuse the connection or there's not going to be another request to the same schema/server/port, I would set KeepAlive to false.
The problem is that XmlDocument.Load() does not read the entire stream before the server closes the connection or that it keeps reading beyond the end and when the server keep-alive timeout is over, the connection is closed by the server. Also, you never close the response stream. To verify that this theory is correct, do something like:
// Optional -> webRequest.KeepAlive = false;
string xml = null;
using (StreamReader reader = new StreamReader (webRequest.GetResponse().GetResponseStream())) {
xml = reader.ReadToEnd ();
}
xmlDoc.LoadXml (xml);
and see if that fixes your problem.