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.)
I'm having troubles authenticated my first scraper against the login page for my hockey pool (just looking to grab the stats once a night for dislaying in a nicer format).
//my variables
string userName = "My Pool";
string password = "hockey";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "ctl00$MainContent$txtPoolName=" + userName + "&ctl00$MainContent$txtPassword=" + password;
byte[] postDataBytes = encoding.GetBytes(postData);
string url = "http://www.pickuphockey.com/hp/hp_login.aspx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Cache-Control: max-age=0");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.Headers.Add("Accept-Encoding: gzip,deflate");
request.Headers.Add("Accept-Language: en-GB,en-US;q=0.8,en;q=0.6");
request.Headers.Add("Upgrade-Insecure-Requests: 1");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
request.ContentLength = postDataBytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Origin: http://www.pickuphockey.com");
request.Referer = "http://www.pickuphockey.com/hp/hp_login.aspx";
request.Host = "www.pickuphockey.com";
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
using (var stream = request.GetRequestStream())
{
stream.Write(postDataBytes, 0, postDataBytes.Length);
stream.Close();
}
//cookie container to save for the next request
var cookieContainer = new CookieContainer();
//get the cookies from the login page
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
foreach (Cookie cookie in response.Cookies)
{
cookieContainer.Add(cookie);
}
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var r = readStream.ReadToEnd();
}
I've been working with various examples throughout Stack Overflow and am using fiddler to analyse the web calls made; trying to match all the headers in the browser login with the headers that I'm adding to my code.
Right now when I code break and look at the variable r, I see the html for a page saying that I need to enter a value for the username/password. I assume this means that I'm not setting the parameters correctly in this call but nothing I read or tweak seems to get past this error. I've masked my actual user/password but I assume that even incorrect values (if someone tries the code) should result in a different error message saying something about a bad password. Any web call gurus out there that can spot what I'm doing wrong?
Once the code works I'll wrap it up into some nicer helper class, I know it's a tad messy at the moment.
Appreciate the time.
I finally found the problem with my parameter string which needs to be formatted depending on the exact page login page I'm trying to access.
string postData = "txtPoolName=" + userName + "&txtPasswordTemp=" + password + "&txtPassword=" + password + "&Submit2=Go";
I figured this part out by using Chrome's inspector on the network traffic when I performed a successful login manually.
What's the easiest way to convert the entire HttpWebRequest to a single string. Similarly to what Fiddler displays when you switch the Fiddler's request pane to the Raw tab?
Thanks for your advice.
Use System.Net.WebClient.
This code combines the HTTP Headers and Body for a Url similar to Fiddler:
string url = "http://stackoverflow.com";
var webClient = new System.Net.WebClient();
var body = webClient.DownloadString(url);
var headers = webClient.ResponseHeaders.ToString();
var raw = headers + "\r\n" + body;
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..
I'm trying to ping Google when my web site's sitemap is updated but I need to know which status code does Google or any other service returns. My code is below:
HttpWebRequest rqst = (HttpWebRequest)WebRequest.Create("http://search.yahooapis.com/ping?sitemap=http%3a%2f%2fhasangursoy.com.tr%2fsitemap.xml");
rqst.Method = "POST";
rqst.ContentType = "text/xml";
rqst.ContentLength = 0;
rqst.Timeout = 3000;
rqst.GetResponse();
You need to use the response - assign it to a HttpWebResponse variable:
HttpWebResponse resp = (HttpWebResponse)rqst.GetResponse();
HttpStatusCode respStatusCode = resp.StatusCode;
The HttpStatusCode enumeration will tell you what status code was returned.
Try HttpWebResponse.StatusCode out