Upload File using httpwebrequest and rest api - c#

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

Related

XML as string content to Post API

I'm trying to POST a XML document to a API URL. The problems is C# special encoding keep creeping into the XML file. the whole XML file.
var content = new StringContent("<XML>", Encoding.UTF8, "text /xml");
var client = new HttpClient();
var result = client.PostAsync("http://localhost/URL", content).Result;
So the that has the password/headerinfo/data how do I get that into a string so C# can read it?
Or should I be doing something different to send an XML file with info to the URL? I am not the API genius either.
I just wound up using a filestream to convert the file to bye array
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}

HP ALM C# REST set attachment for requirement

I've seen many different 'answers' to this, none of them complete. This is my current code for my upload function. It should be complete enough for discussion. I'm getting a (500) error when attempting to upload a .png file. The .png file gets consumed by the formbytes stream, but when it gets to the actual request on the last line, it throws the error. HELP!
public void Upload(string uri, string filePath)
{
FileInfo fi = new FileInfo(filePath);
string fileType = fi.Extension.Replace(".", "");
string slug = fi.Name.Replace(fi.Extension, "");
string formdataTemplate = "Content-Disposition: form-data; name=\"file\" filename=\"{0}\";\r\nContent-Type: application/octet-stream\r\n\r\n";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "application/json";
if (cookies != null)
{
// cookies is a cookie container populated by another process, works for creating ALM requirements
request.CookieContainer = cookies;
}
request.Headers.Add("slug", slug);
string formitem = "";
byte[] formbytes = null;
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));
formbytes = Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formbytes, 0, formbytes.Length);
byte[] buffer = new byte[1024 * 4];
int bytesLeft = 0;
while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesLeft);
}
}
}
//request.Headers.Add(formbytes);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { }
}
The answer is that I had to check-out the requirement to add the attachment. It's a simple post, with no body needed, to :
/rest/domains/[domain]/projects/[project]/requirements/[entityId]/versions/check-out
and you can check-in, also no body needed:
/rest/domains/[domain]/projects/[project]/requirements/[entityId]/versions/check-out

UNICODE encoding of central European languages

Does not recognize the uncoding what to do?
var url = "http://translate.google.ru/translate_a/t?client=x&text=" + text + "&hl=en&sl=en&tl=ru";
new System.Net.WebClient().DownloadFile(url, "filePath");
StreamReader streamReader = new StreamReader("filePath", Encoding.UTF8);
string trn = streamReader.ReadToEnd();
streamReader.Close();
return trn;
Label1.Text = tr.GoogleTranslate("testers");
Result: �������
Here how you can read that using the WebRequest
HttpWebResponse response = null;
StreamReader reader = null;
Stream dataStream = null;
StringBuilder sbReadBuffer = null;
int bufSizeMin = 8192;
int bufSizeMax = 65536;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(TheWebPageToRead);
if (req != null)
{
req.Method = "GET";
response = (HttpWebResponse)req.GetResponse();
if (response != null)
{
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream, true);
// get the length of the content returned by the request
int length = (int)response.ContentLength;
int bufSize = bufSizeMin;
if (length > bufSize)
bufSize = length > bufSizeMax ? bufSizeMax : length;
// allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
sbReadBuffer = new StringBuilder(bufSize);
// read the whole response
while ((length = dataStream.Read(buf, 0, buf.Length)) != 0){
sbReadBuffer.Append(Encoding.UTF8.GetString(buf, 0, length));
}
}
}
}
finally
{
if (response != null)
response.Close();
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
}
The TheWebPageToRead is yours url.
The sbReadBuffer keeps the return and asking for "testers" I get:
{"sentences":[{"trans":"Тестеры","orig":"testers","translit":"Testery","src_translit":""}],"src":"en","server_time":11}
asking for "aristos", I get: {"sentences":[{"trans":"аристократов","orig":"aristos","translit":"aristokratov","src_translit":""}],"src":"en","server_time":5}

Uploading picture to picasa web

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");

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;
}

Categories

Resources