问题
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
回答1:
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();
}
回答2:
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");
来源:https://stackoverflow.com/questions/6577846/uploading-picture-to-picasa-web