Uploading picture to picasa web - c#

I m trying to upload a new photo to picasa using the API.
code not working
I am getting the following error:
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.
My Code:
string imgPath = "C:\foo.png";
StreamReader reader = new StreamReader(imgPath);
string imgBin = reader.ReadToEnd();
reader.Close();
string id=""//picasa ID
string album = "";//album name
string url = String.Format("http://www.picasaweb.google.com/data/feed/api/user/{0}/album/{1}",id, album);
string auth = "";
Byte[] send = Encoding.UTF8.GetBytes(imgBin);
int length = send.Length;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "image/png";
req.ContentLength = length;
req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
req.Headers.Add("Slug", "test");
Stream stream = req.GetRequestStream();
stream.Write(send, 0, length);
stream.Close();
WebResponse response = req.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string res = reader.ReadToEnd();
reader.Close();
Thanks

The problem is most likely with how you are reading the image. Instead of reading it as a string, try writing it directly into the request stream, similar to the following:
using (Stream fileStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "image/png";
request.ContentLength = fileStream.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + auth);
request.Headers.Add("Slug", "test");
using (Stream requestStream = request.GetRequestStream())
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseStr = responseReader.ReadToEnd();
}

string username = form["UserName"].ToString(); // <-- ### USERNAME HERE ###
string password = form["Password"].ToString(); // <-- ### PASSWORD HERE ###
PicasaService picasaService = new PicasaService("Tester");
picasaService.setUserCredentials(username, password);
// 2. Create a test album
//
AlbumEntry entry = new AlbumEntry();
entry.Title.Text = "test-69";
entry.Summary.Text = "test-69";
AlbumAccessor access = new AlbumAccessor(entry);
PicasaEntry album = picasaService.Insert(new Uri(PicasaQuery.CreatePicasaUri(username)), entry);
access = new AlbumAccessor(album);
// 3. Upload a photo
picasaService.Insert(new Uri(PhotoQuery.CreatePicasaUri(username, access.Id)), System.IO.File.OpenRead("thumb-1.jpg"), "image/jpeg", "thumb-1.jpg");

Related

Getting error only when value is passed in json string in httpwebrequest

I am peforming HttpWebRequest to perform POST method. I get error only when I pass value otherwise It's working perfectly.
Code:
public void CreateOrganization(string accountname)
{
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = "{\"name\":\" "+accountname+" \"}";
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
}
It stops working at Stream newStream = http.GetRequestStream(); .

Send an HTTP POST request with C#

I'm try to Send Data Using the WebRequest with POST But my problem is No data has be streamed to the server.
string user = textBox1.Text;
string password = textBox2.Text;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username" + user + "&password" + password;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr99 = new StreamReader(stream);
MessageBox.Show(sr99.ReadToEnd());
sr99.Close();
stream.Close();
here the result
It's because you need to assign your posted parameters with the = equal sign:
byte[] data = Encoding.ASCII.GetBytes(
$"username={user}&password={password}");
WebRequest request = WebRequest.Create("http://localhost/s/test3.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
MessageBox.Show(responseContent);
See the username= and &password= in post data formatting.
You can test it on this fiddle.
Edit :
It seems that your PHP script has parameters named diffently than those used in your question.

Upload File using httpwebrequest and rest api

I am trying to upload file using httpwebrequest and rest api
My code is like this i am not getting any error but i cannt able to upload file.
public static string RequestProfileUrl = "https://ws.onehub.com/workspaces/337426/folders/174352646/files/create?items[filename]=";
if (file != null && file.ContentLength > 0)
{
byte[] bytearray = null;
string name = "";
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
name = file.FileName;
Stream stream = file.InputStream;
stream.Seek(0, SeekOrigin.Begin);
bytearray = new byte[stream.Length];
int count = 0;
Stream memStream = new System.IO.MemoryStream();
while (count < stream.Length)
{
bytearray[count++] = Convert.ToByte(stream.ReadByte());
}
//string baseAddress = "https://ws-api.onehub.com/workspaces/330201/files/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(RequestProfileUrl + name);
request.Method = "PUT";
request.ContentType = "multipart/form-data";
request.ContentLength = bytearray.Length;
request.GetRequestStream().Write(bytearray, 0, bytearray.Length);
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
}
i am not getting any error but my file is not uploading. i am not getting where is my error?
any question free to ask
Thanks in advance

How to Download the File using HttpWebRequest and HttpWebResponse class(Cookies,Credentials,etc.)

Thanks icktoofay,
I tried using HttpWebRequest and HttpWebResponse.
When I request for URL by passing the Credentials like UserName And Password.
I will get the Session Id Back in the Response.
After getting that Session Id, How to Move Further.
The authenticated user are tracked using credentials/cookies.
I'm Having the Exact Url of the File to be downloaded and credentials.
If you want to use Cookies I will. I need to read the File Data and write/save it in a Specified Location.
The code I'm using is;
string username = "";
string password = "";
string reqString = "https://xxxx.com?FileNAme=asfhasf.mro" + "?" +
"username=" + username + &password=" + password;
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
string s1;
CookieContainer cc = new CookieContainer();
var request = (HttpWebRequest)WebRequest.Create(loginUri);
request.Proxy = null;
request.CookieContainer = cc;
request.Method = "POST";
HttpWebResponse ws = (HttpWebResponse)request.GetResponse();
Stream str = ws.GetResponseStream();
//ws.Cookies
//var request1 = (HttpWebRequest)WebRequest.Create(loginUri);
byte[] inBuf = new byte[100000];
int bytesToRead = (int) inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = str.Read(inBuf, bytesRead,bytesToRead);
if (n==0)
break;
bytesRead += n;
bytesToRead -= n;
}
FileStream fstr = new FileStream("weather.jpg", FileMode.OpenOrCreate,
FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();
This is how I do it:
const string baseurl = "http://www.some......thing.com/";
CookieContainer cookie;
The first method logins to web server and gets session id:
public Method1(string user, string password) {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string login = string.Format("go=&Fuser={0}&Fpass={1}", user, password);
byte[] postbuf = Encoding.ASCII.GetBytes(login);
req.ContentLength = postbuf.Length;
Stream rs = req.GetRequestStream();
rs.Write(postbuf,0,postbuf.Length);
rs.Close();
cookie = req.CookieContainer = new CookieContainer();
WebResponse resp = req.GetResponse();
resp.Close();
}
The other method gets the file from server:
string GetPage(string path) {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(path);
req.CookieContainer = cookie;
WebResponse resp = req.GetResponse();
string t = new StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd();
return IsoToWin1250(t);
}
Note that I return the page as string. You would probably better return it as bytes[] to save to disk. If your jpeg files are small (they usually are not gigabyte in size), you can simply put them to memory stream, and then save to disk. It will take some 2 or 3 simple lines in C#, and not 30 lines of tough code with potential dangerous memory leaks like you provided above.
public override DownloadItems GetItemStream(string itemID, object config = null, string downloadURL = null, string filePath = null, string)
{
DownloadItems downloadItems = new DownloadItems();
try
{
if (!string.IsNullOrEmpty(filePath))
{
using (FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
if (!string.IsNullOrEmpty(downloadURL))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadURL);
request.Method = WebRequestMethods.Http.Get;
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
const int BUFFER_SIZE = 16 * 1024;
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var buffer = new byte[BUFFER_SIZE];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE);
fileStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
fileStream.Close();
downloadItems.IsSuccess = true;
}
}
else
downloadItems.IsSuccess = false;
}
}
}
catch (Exception ex)
{
downloadItems.IsSuccess = false;
downloadItems.Exception = ex;
}
return downloadItems;
}

How to simulate browser file upload with HttpWebRequest

guys, first of all thanks for your contributions, I've found great responses here. Yet I've ran into a problem I can't figure out and if someone could provide any help, it would be greatly appreciated.
I'm developing this application in C# that could upload an image from computer to user photoblog. For this I'm usig pixelpost platform for photoblogs that is written mainly in PHP.
I've searched here and on other web pages, but the exmples provided there didn't work for me.
Here is what I used in my example: (Upload files with HTTPWebrequest (multipart/form-data))
and
(http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code)
Once it is ready I will make it available for free on the internet and maybe also create a windows mobile version of it, since I'm a fan of pixelpost.
here is the code I've used:
string formUrl = "http://localhost/pixelpost/admin/index.php?x=login";
string formParams = string.Format("user={0}&password={1}", "user-String", "password-String");
string cookieHeader;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.AllowAutoRedirect = false;
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
cookieHeader = resp.Headers["Set-Cookie"];
string pageSource;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
Console.WriteLine();
}
string getUrl = "http://localhost/pixelpost/admin/index.php";
HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
// end first part: login to admin panel
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save");
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.AllowAutoRedirect = false;
httpWebRequest2.KeepAlive = false;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest2.Headers.Add("Cookie", cookieHeader);
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string formitem = string.Format(formdataTemplate, "headline", "image-name");
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
string header = string.Format(headerTemplate, "userfile", "path-to-the-local-file");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream("path-to-the-local-file", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
Console.WriteLine(reader2.ReadToEnd());
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
and also here is the PHP:
(http://dl.dropbox.com/u/3149888/index.php)
and
(http://dl.dropbox.com/u/3149888/new_image.php)
the mandatory fields are headline and userfile so I can't figure out where the mistake is, as the format sent in right. I'm guessing there is something wrong with the octet-stream sent to the form.
Maybe it's a stupid mistake I wasn't able to trace, in any case, if you could help me that would mean a lot.
thanks,
So Martin helped me out here and I was able to make the important changes to the code above in order for it to work properly.
The Content-Type had to be changed to image/jpeg. Also I used C# Image type to send image stream.
Also pay attention to the Stream format, as it does not have to contain extra spaces or new lines.
here is the changed part:
string formUrl = "http://localhost/pixelpost/admin/index.php?x=login";
string formParams = string.Format("user={0}&password={1}", "username", "password");
string cookieHeader;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.AllowAutoRedirect = false;
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
cookieHeader = resp.Headers["Set-Cookie"];
string pageSource;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
string getUrl = "http://localhost/pixelpost/admin/index.php";
HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save");
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.AllowAutoRedirect = false;
httpWebRequest2.KeepAlive = false;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest2.Headers.Add("Cookie", cookieHeader);
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary);
string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg\r\n\r\n";
string header = string.Format(headerTemplate, "userfile", "Sunset.jpg");
byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
Image img = null;
img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true);
img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string formitem = string.Format(formdataTemplate, "headline", "Sunset");
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
Console.WriteLine(reader2.ReadToEnd());
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
Thank you all again for answering or just reading.

Categories

Resources