WP Rest API - Upload image to WP using Restsharp - wordpress

I have a problem uploading an image to Wordpress from a VB .NET project (using Restsharp). I create the client and the request for this, I added a header with the authorization, parameters...) but, when I execute the request, this response Status OK (200) but the image has not create in Wordpress.
I tried all this sentences, and no works:
Test 1:
Dim client As RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request As RestRequest = New RestRequest(Method.POST)
request.AddHeader("Authorization", "Basic {base64code}")
request.AddHeader("Cookie", "PHPSESSID=b83jbtsfjbb2bkkso7s75m75il")
request.AddHeader("Content-Disposition", "attachment; filename=Google-logo.jpg")
request.AddHeader("Content-Type", "image/jpeg")
request.AddFile("file", "C:\temp\Google-logo.jpg")
request.AddParameter("title", "titleExample")
request.AddParameter("caption", "captionExample")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.StatusCode)
Test 2:
Dim client As RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request As RestRequest = New RestRequest(Method.POST)
request.AddHeader("Authorization", "Basic {base64code}")
request.AddHeader("Cookie", "PHPSESSID=b83jbtsfjbb2bkkso7s75m75il")
request.AddParameter("title", "titleExample")
request.AddParameter("caption", "captionExample")
request.AlwaysMultipartFormData = True
request.AddParameter("file", "C:\temp\Google-logo.png")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.StatusCode)
Test 3:
Dim client as RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request = New RestRequest(Method.POST)
request.RequestFormat = DataFormat.Json
request.AddHeader("Authorization", "Basic {base64code}")
request.AddFileBytes("file", BytesImage, "C:\temp\Google-logo.jpg", "image/jpeg")
request.AddParameter("title", "tempFile")
request.AddParameter("caption", "tempFileCaption")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.Content)
Test 4: In this example I not use RestSharp, I used the HttpWebRequest, and the same result
Dim myReq As HttpWebRequest
Dim myResp As HttpWebResponse
myReq = HttpWebRequest.Create("http://domain-example.com/wp-json/wp/v2/media")
myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:password")))
Dim myData As String = "c:\temp\Google-logo.jpg"
myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
myResp = myReq.GetResponse
Dim myreader As New System.IO.StreamReader(myResp.GetResponseStream)
Dim myText As String
myText = myreader.ReadToEnd
I tried to simulate the upload using Postman, but I can't.
I don't know why it's so hard to upload an image to Wordpress using REST...
Disclaimer:
Also, this post doesn't work for me

The following is from the docs.
To add a file to the request you can use the RestRequest function called AddFile. The main function accepts the FileParameter argument:
request.AddFile(fileParameter);
You can instantiate the file parameter using FileParameter.Create that accepts a bytes array or FileParameter.FromFile, which will load the file from disk.
There are also extension functions that wrap the creation of FileParameter inside:
// Adds a file from disk
AddFile(parameterName, filePath, contentType);
// Adds an array of bytes
AddFile(parameterName, bytes, fileName, contentType);
// Adds a stream returned by the getFile function
AddFile(parameterName, getFile, fileName, contentType);
Remember that AddFile will set all the necessary headers, so please don't try to set content headers manually. Your code sets a lot of content headers, and it's unnecessary, and might be breaking your requests.
You can always use https://requestbin.com and send your requests there to inspect the content of those requests, so you can see if they match the expected request format.

In test 1, remove or comment out this line of code:
request.AddHeader("Content-Type", "image/jpeg")

The solution for this is activate the JWT authentication plugin for Wordpress. By default, Wordpress avoid any POST call, the basic authentication doesn't work.
So, once activated the JWT (following the process), you must create a Token (using POST to the JWT endpoint) and put the Token in the POST process to create anything (posts, media, etc.)

Related

SagePay RedirectURL failure

Using server integration and .net, I post the original request to SagePay and get the NextURL fine, and so go to the payment pages... step through them OK, but then I get the error:
Server error 5006: Unable to redirect to Vendor's web site. The Vendor failed to provide a RedirectionURL.
HTTP error 500: The request was unsuccessful due to an unexpected condition encountered by the server.
But I am sending a RedirectionURL (though the docs call is RedirectURL, which is somewhat confusing - anyway, I've tried using both. This si what I'm sending back from my NotificatioURL - what's wrong?
Dim sb As New StringBuilder
sb.Append("Status=OK")
sb.Append("&StatusDetail=Fine")
sb.Append("&RedirectURL=https://mydomain.co.uk/sagepay.aspx")
Dim urlTEST As String = "https://test.sagepay.com/gateway/service/vspserver-register.vsp"
Dim urlLIVE As String = "https://live.sagepay.com/gateway/service/vspserver-register.vsp"
Try
Dim data As Byte() = Encoding.UTF8.GetBytes(sb.ToString)
Dim request As WebRequest = WebRequest.Create(urlTEST)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = data.Length
ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateRemoteSSLCertificate
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim stream = request.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()
Dim response As WebResponse = request.GetResponse()
response.Close()
Catch ex As Exception
'log error
End Try
Update: I gather this POST (unlike the initial one with the basket info) requires that the data be sent plain text key-value pairs separated by CrLf's, so I amended this to
Dim sb As New StringBuilder
sb.AppendLine("Status=OK")
sb.AppendLine("StatusDetail=Fine")
sb.Append("RedirectURL=https://mydomain.co.uk/sagepay.aspx")
but it still fails with the same errors. I also tried using, instead of the WebRequst class, the simpler:
Dim client As WebClient = New WebClient()
Dim reply As String = client.UploadString(urlTEST, sb.ToString)
But still no joy. Also tried changing the request.ContentType to "text/plain", but nope.
Come on, someone, please - this si basic to the their operations, someone must have done it....
Blimey - it never pays to be clever. This script doesn't require WebRequest or anything, just write to the simple Response object. Sigh.. as Linus said ....

sending email with attachment from Azure using SendGrid

How do I send an email with an attachment using SendGrid, from my VM in Azure?
I added myMsg.AddAttachment and supplied the parameters. I get no errors when I execute, but Email never gets sent. If I comment out this line,
email gets sent.
What am I doing wrong? This is in ASP.net VB.
I used Sendgrid 9.9.0 to check this issue, here is the code snippet:
'instantiate the SendGridMessage object
Dim sendGridMessage = New SendGridMessage()
sendGridMessage.From = New EmailAddress("xxxxxx#hotmail.com", "BruceChen1019")
sendGridMessage.AddTo(New EmailAddress("xxxxx#gmail.com", "Bruce Chen"))
sendGridMessage.PlainTextContent = "Hello World!"
sendGridMessage.Subject = "Hello Email!"
'instantiate the Attachment object
Dim attachment = New Attachment()
attachment.Filename = "helloword.txt"
attachment.Content = Convert.ToBase64String(Encoding.UTF8.GetBytes("hello world!!!"))
attachment.Type = "text/plain"
Dim attachments = New List(Of Attachment)
attachments.Add(attachment)
sendGridMessage.AddAttachments(attachments)
'send the email
Dim Response = client.SendEmailAsync(sendGridMessage).Result
Console.WriteLine(Response.StatusCode) //202 Accepted
Console.ReadLine()
TEST:
Moreover, for your attachment file, you need to set the correct MIME Type for attachment.Type based on the file extension, and Base64 encode your file content.
Also, you need to follow the Attachments limitations. And you may follow evilSnobu's comment about going to SendGrid portal for troubleshooting this issue.

Google Analytics API - Retrieve refresh token with OAuth2 & ASP.NET

I'm trying to set up offline access for a Google Analytics API application using OAuth2 and I'm using ASP.NET to POST my authorization code in exchange for a refresh token but I can't get a response from the server to give me the refresh token.
I've used the example code from the MSDN documentation for a post request so I can only assume this is correct, however I receive the error message "The remote server returned an error: (400) Bad Request at System.Net.HttpWebRequest.GetResponse()":
using System;
using System.IO;
using System.Net;
using System.Text;
WebRequest request = WebRequest.Create ("https://accounts.google.com/o/oauth2/token?code=xxxmyauthorizationcodexxx&client_id=xxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxx&redirect_uri=https://mysite.com/oauth2callback&grant_type=authorization_code");
request.Method = "POST";
string postData = "code=xxxmyauthorizationcodexxx&client_id=xxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxx&redirect_uri=https://mysite.com/oauth2callback&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
WebResponse response = request.GetResponse ();
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
reader.Close ();
dataStream.Close ();
response.Close ();
I have successfully used the GET method to retrieve the authorization code to begin with and I'm following this documentation: https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse
I'm also using a https website to make the requests and I'm manually refreshing my authorization code as it expires. Does anyone have a solution for this problem?
EDIT: For anyone experiencing the same issue, firstly look at aeijdenberg's response below, but my solution was that the authorization code I used for the code parameters expires pretty instantaneously - I kept refreshing my page without request a new one. To get the data just display the content from the responseFromServer variable.
It looks like you are passing the parameters twice. Once in the query string:
WebRequest request = WebRequest.Create ("https://accounts.google.com/o/oauth2/token?code=xxxx...
And then again as POST data. I would suggest removing the query string, e.g. POST directly to "https://accounts.google.com/o/oauth2/token".
Also suggesting ensuring that all parameters are URL encoded if you're not already doing so:
http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx

mvaayoo api issue for sending messages from a website

i am using mvaayoo api for sending the messages from my website.
i have read the documentation and do the same even then i am not able to send the messages.
i am using this sample code
string strUrl = "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=
Username:Password&senderID=mVaayoo&receipientno=919849558211&msgtxt=This is a test from mVaayoo API&state=4";
WebRequest request = HttpWebRequest.Create(strUrl);
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse();
Stream s = (Stream)response.GetResponseStream();
StreamReader readStream = new StreamReader( s );
string dataString = readStream.ReadToEnd();
response.Close();
s.Close();
readStream.Close();
Help me please
Thanks,
Rajbir
I think the problem is because of the space in URL.
Use this for URL ;
string strUrl = "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=
Username:Password&senderID=mVaayoo&receipientno=919849558211&msgtxt=This%20is%20a%20test%20from%20mVaayoo%20API&state=4";
I replaced all space with %20 in the URL. I suffered with the same problem in java.. so it should work..

Send HTTP Command using VB.NET

I'm trying to send an HTTP command using VB.NET and I'm not quite sure how to do it. I don't want to actually navigate to the page, just execute the command.
http://xbmc.local/xbmcCmds/xbmcHttp?command=ExecBuiltIn&parameter=XBMC.updatelibrary%28video%29
What I'm doing is building an integrated interface for my XBMC home theater, and my home automation.
You can use the WebRequest object to send an HTTP Request.
' Create a WebRequest object with the specified url. '
Dim myWebRequest As WebRequest = WebRequest.Create(url)
' Send the WebRequest and wait for response. '
Dim myWebResponse As WebResponse = myWebRequest.GetResponse()
The WebResponse class has a number of properties you can check to see if the request succeeded or not. And just something to be aware of, GetResponse() will throw an exception if it times out.
Try the following
Dim client = WebRequest.Create("http://xbmc.local/xbmcCmds/xbmcHttp?command=ExecBuiltIn&parameter=XBMC.updatelibrary%28video%29")
Dim response = client.GetResponse()

Resources