Send document to zoom chat via java program - api

I'm trying to send a file using zoom api, and I have a OAuth server-to-server authentication with /chat_message:write:admin in my app scope and I have tested simple message without problems. I already have a token, my ID and my recipient's ID.
My program runs and returns error 405 method not allowed.
I choose to send label.pdf file.
Zoom documentation page is: link to zoom api send document
private static final String API_ENDPOINT = "https://api.zoom.us/v2/chat/users/";
// Create API URL
URL url = new URL(API_ENDPOINT + userId + "/messages/files");
// Open connection and set request properties
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + token);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=boundary");
byte[] pdfData = Files.readAllBytes(new File(filePath).toPath());
String boundary = "boundary";
String delimiter = "--" + boundary + "\r\n";
StringBuilder builder = new StringBuilder();
builder.append(delimiter);
builder.append("Content-Disposition: form-data; name=\"to_contact\"\r\n\r\n");
builder.append(toContact+"\r\n");
builder.append(delimiter);
builder.append("Content-Disposition: form-data; name=\"files\"; filename=\"label\"\r\n");
builder.append("Content-Type: application/pdf\r\n");
builder.append("\r\n");
builder.append(new String(pdfData, "ISO-8859-1"));
builder.append("\r\n");
builder.append("--" + boundary + "--");
conn.setDoOutput(true);
String multipartData = builder.toString();
System.out.println(multipartData);
conn.getOutputStream().write(multipartData.getBytes("UTF-8"));
// Send request and get response code and message
conn.connect();
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
// Check if response is successful
if (Arrays.asList(RESPONSE_CODE).contains(Integer.toString(responseCode))) {
System.out.println("File sent successfully!");
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
} else {
System.out.println("Error sending file:");
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
}
// Close connection
conn.disconnect();
Can anyone suggest me what's wrong?

Related

Requesting a API token with both basic authentication and application/x-www-form-urlencoded

I'm trying to create an application using MS Visual Studio in either vb.net or C# to receive a token for a web api that has both basic authentication and application/x-www-form-urlencoded. When I send the request from Postman the requested works. Please see Postman screen shots below. When is use the below code I receive and message "Request failed with status code NotFound" back and the request fails. Can any point in the the right direction to resolve this.
Thank you
Postman
postman body
`private void button1_Click(object sender, EventArgs e)
{
Uri baseurl = new Uri("https://api address/token");
RestClient client = new RestClient(baseurl);
//client.Timeout = -1;
RestRequest request = new RestRequest("post", Method.Post);
request.AddHeader("Authorization", "Basic M2U4Y");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials",true);
request.AddParameter("scope", "https://?????????",true);
RestResponse response = client.Execute(request);
if (response.Content == "")
{
textBox1.Text = response.ErrorException.Message ;
}
else
{
textBox1.Text = response.Content;
}
}
`
I solved the problem. With the below code.
Uri baseurl = new Uri("https://api address/token");
RestClient client = new RestClient(baseurl);
RestRequest request = new RestRequest(baseurl, Method.Post);
request.AddHeader("Authorization", "Basic M2U4Y");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=https://FED0C291",arameterType.RequestBody);RestResponse response = client.Execute(request);
if (response.Content == "")
{
textBox1.Text = response.ErrorException.Message ;
}
else
{
textBox1.Text = response.Content;
}

How to encode JSON Url in ASP.NET Core

I want to make a post to an API, and the link I'm using to make the post call has some URL parameters.
Link to make post: http://someservice/api/v1/requests?input_data=encoded_data
The parameter (input_data) is a JSON that needs to be encoded before.
When I use this link to encode the below JSON, and I add the encoded result to the URL and make the post with Postman, it works just fine.
{
"request":{
"requester":{
"email_id":"**phx#phx.com**"
},
"subject":"**subject**",
"description":"**description something**"
}
}
This is what I have in my method:
[HttpPost]
[Route("projectRequest")]
[Consumes("multipart/form-data")]
public IActionResult CreateConfig([FromForm] ConfigInputModel model) {
try {
var json =
"{" +
"\"request\":{ " +
"\"requester\":{ " +
"\"email_id\" : \" " + model.Requester + " \" " +
"}," +
"\"subject\":\" " + model.Subject + " \" \", " +
"\"description\":\" " + model.Description + " \" \" " +
"}" +
"}";
HttpClient httpClient = new HttpClient();
Encoding utf16le = new UnicodeEncoding(bigEndian: false, byteOrderMark: true,throwOnInvalidBytes: true);
HttpContent content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(json));
var postResponse = httpClient.PostAsync("http://someservice/api/v1/requests?input_data=" +
System.Web.HttpUtility.UrlEncode(json), content);
return Ok(postResponse.Result);
} catch (Exception e) {
return NotFound();
}
}
My question is how can I encode the JSON variable, because I'm getting
"Unable to parse the JSON"
response from the API. I suspect the escape characters in the JSON string I have are causing it, but can't figure it out for quite a while. Thanks.
Instead of writing JSON as a string, would suggest setting the data as object with POCO class or anonymous type. And next, serialize it to a JSON string.
Benefit: Avoid JSON syntax errors.
anonymous type
var json = new {
request = new {
requester = new {
email_id = model.Requester
}
},
subject = model.Subject,
description = model.Description
};
Console.WriteLine(JsonConvert.SerializeObject(json));
Sample program
Output
{"request":{"requester":{"email_id":"Requester"}},"subject":"Subject","description":"Description"}
I test your code in my side and when I using JObject jsonObj = JObject.Parse(json); to transfer your json string, I got the error about request.subject and request.description,
then I found you made a mistake in this place, you should remove what I marked in the screenshot below.

One Drive API returns invalid Access Token

The authentication process is not working now.(It was working earlier). By following the documentation I'm trying to get the access token from a refresh token. I successfully can get a access token. But it's not valid. I'm setting it as Bearer and send it in my GET request and it returns the following JSON
{"error":{"code":"accessDenied","message":"Access Denied"}}
Here is the code sample
String messageBody = "client_id=" + "9b1a6dbb-7e1f-41b5-b448-9f328169411e" + "&redirect_uri=" + returnURL + "&client_secret={cleindsecret}
+ "&refresh_token={refreshtoken}&grant_type=refresh_token";
RequestBody oAuthCodeRedeemBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
messageBody);
Request request = new Request.Builder().url("https://login.live.com/oauth20_token.srf")
.post(oAuthCodeRedeemBody).build();
String responseBody = null;
OkHttpClient client = new OkHttpClient();
client.setFollowRedirects(false);
Response response;
String accessToken = null;
try {
response = client.newCall(request).execute();
responseBody = response.body().string();
resp = (JSONObject) jsonParser.parse(responseBody);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
accessToken = (String) resp.get("access_token");
I'm getting a Access Token here. But I can't use it to do any work.
Request request2 = new Request.Builder().url("https://api.onedrive.com/v1.0/drive/items/1ED8983F38E94F01!107/children").header("Authorization", "Bearer " + accessToken).get().build();
The response for the above code is returned as
{"error":{"code":"accessDenied","message":"Access Denied"}}
What is the reason here. Is the API returning me a invalid access token or is something wrong in my code?

Do I have to use SSL with Paypal? How do I set Paypal on Windows Azure?

I am putting online an old web application I had running like 3 years ago.
Back then everything worked and Paypal's ExpressCheckout was set perfectly.
I really cannot remember what I was doing back then but now I put my app on Windows Azure. My app is written in ASP.NET MVC5.
The following piece of code might look familiar for those of you who implemented Paypal inside your apps and its probably taken from Paypal's documentation and used for posing to Paypal's server:
/// <summary>
/// HttpCall: The main method that is used for all API calls
/// </summary>
/// <param name="NvpRequest"></param>
/// <returns></returns>
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost, 0, strPost.Length);
}
}
catch (Exception e)
{
CommonFuncs.Log(MyGlobals.LOG_FILE_DO_EXPRESS_CHECKOUT, e.Message);
return null;
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
Now, when I'm trying to POST (here)
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost, 0, strPost.Length);
}
I am getting the following error message
The request was aborted: Could not create SSL/TLS secure channel.
Does it mean that I have to purchase an SSL certificate? or is there something I just need to tweek on Azure so it will work?
No need to purchase an SSL. But you can upgrade your certificate into SHA 256 and TLS 1.2. Refer to the link below.
https://www.paypal-knowledge.com/infocenter/index?page=content&id=FAQ1913
and
https://github.com/paypal/TLS-update
Thank you #PP_MTS_Steven.
I can't remember the source on SO which gave me the solution. However, all I did was to put this two lines of code:
ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Right here:
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
...
And things started working.

Eventbrite OAUTH2 login on windows store apps keep me get BAD REQUEST

I got problem on oauth2 handshake, as the eventbrite documentation is not very clear.
http://developer.eventbrite.com/doc/authentication/oauth2/ -> number 4
what i currently do is like this
WebRequest webRequest = WebRequest.Create("https://www.eventbrite.com/oauth/token");
string URLEncoded = "code=" + token + "&client_secret=" + APISecret + "&client_id=" + APIKey + "&grant_type=authorization_code";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(URLEncoded);
Stream os = null;
try
{
os = await webRequest.GetRequestStreamAsync();
os.Write(bytes, 0, bytes.Length);
WebResponse response = await webRequest.GetResponseAsync();
os = response.GetResponseStream();
StreamReader reader = new StreamReader(os);
string responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
string err = ex.ToString();
}
finally
{
if (os != null)
{
os.Dispose();
}
}
Can someone give tips on this? i keep getting BAD REQUEST as a result. Thank you
edited : the response say : code is invalid or expired
I know its clear, but i already implement and get the token to exchange, use Secret API key and API Key to get it, but how come its invalid/expired?