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}
Related
In the below sample code, streamSupportsReading is false.
private void SomeFunction()
{
HttpWebResponse responseObj = GetFile();
bool streamSupportsReading = responseObj.GetResponseStream().CanRead;
}
private HttpWebResponse GetFile()
{
var request = (HttpWebRequest)HttpWebRequest.Create("URL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
using (var bytes = new MemoryStream())
{
var buffer = new byte[256];
while (bytes.Length < response.ContentLength)
{
var read = stream.Read(buffer, 0, buffer.Length);
//code to calculate download percentage
}
}
}
return response;
}
It's because you put response.GetResponseStream() in a using block, so it gets disposed before GetFile() returns, making it unusable.
If you were to not dispose it, then CanRead would still be true:
private HttpWebResponse GetFile()
{
var request = (HttpWebRequest)HttpWebRequest.Create("URL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
using (var bytes = new MemoryStream())
{
var buffer = new byte[256];
while (bytes.Length < response.ContentLength)
{
var read = stream.Read(buffer, 0, buffer.Length);
//code to calculate download percentage
}
}
return response;
}
I'm working on an app that makes a POST to a REST API that returns a URI in its response. I then am to make a GET request to that URI and it is supposed to return HTML content in the response body. However, the GET request returns 'No Content' in its HTTP Status Code.
What's strange is, I have a small console app I built for testing purposes that if I plug the URI into it (allows me to test the GET without making the POST), the status good is 200 - OK and I receive the HTML content in the body. So it seems it is related to something I'm doing in my POST request. Here is my code (sensitive info has been redacted):
private PersonReportResults POSTReportRequest(PersonReportRequest reportRequest)
{
var personReportResults = new PersonReportResults();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxxxxxx.com/api/v1/personReport/reportResults");
var xDoc = new XmlDocument();
var serializedXml = Serialize(reportRequest);
xDoc.LoadXml(serializedXml);
var bytes = Encoding.ASCII.GetBytes(xDoc.OuterXml);
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["XXXXXUserId"], ConfigurationManager.AppSettings["XXXXXPassword"]);
request.ClientCertificates.Add(GetClientCertificate());
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseStream = response.GetResponseStream();
using (MemoryStream ms = new MemoryStream())
{
var count = 0;
do
{
byte[] buf = new byte[1024];
count = responseStream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (responseStream.CanRead && count > 0);
ms.Position = 0;
// now attempt to desrialize from the memory stream
var serializer = new XmlSerializer(typeof(PersonReportResults));
personReportResults = ((PersonReportResults)serializer.Deserialize(ms));
}
response.Close();
}
request.Abort();
}
return personReportResults;
}
/// <summary>
/// Makes a HTTP GET request for the report HTML
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns>string</returns>
private static string GETResults(string uri)
{
var responseHTML = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + "?reportType=html");
//request.ContentType = "application/xml; encoding='utf-8'";
request.Method = "GET";
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["XXXXXUserId"], ConfigurationManager.AppSettings["XXXXXPassword"]);
request.ClientCertificates.Add(GetClientCertificate());
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (MemoryStream ms = new MemoryStream())
{
var count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
ms.Position = 0;
var sr = new StreamReader(ms);
responseHTML = sr.ReadToEnd();
}
//var reader = new StreamReader(stream, Encoding.UTF8);
//responseHTML = reader.ReadToEnd();
}
}
}
catch (Exception e)
{
}
request.Abort();
}
else if (response.StatusCode == HttpStatusCode.Accepted)
{
response.Close();
var tryCount = 1;
while (tryCount < 5)
{
using (var retryResponse = (HttpWebResponse)request.GetResponse())
{
if (retryResponse.StatusCode == HttpStatusCode.OK)
{
using (var stream = retryResponse.GetResponseStream())
{
if (stream != null)
{
var reader = new StreamReader(stream, Encoding.UTF8);
responseHTML = reader.ReadToEnd();
}
}
}
}
tryCount++;
Thread.Sleep(10000);
}
}
}
return responseHTML;
}
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
I need to read the content of a webpage in streamreader like
www.example.com
<test>
<sample></sample>
</test>
i got this:
System.IO.StreamReader StreamReader1 =
new System.IO.StreamReader("www.example.com");
string test = StreamReader1.ReadToEnd();
but i then i get this error code
Attempt to access the method failed:
System.IO.StreamReader..ctor(System.String)
Try a WebClient, it's easier and you don't have to worry about streams and rivers:
using (var client = new WebClient())
{
string result = client.DownloadString("http://www.example.com");
// TODO: do something with the downloaded result from the remote
// web site
}
If you want to use the StreamReader, here is the code I am using:
const int Buffer_Size = 100 * 1024;
WebRequest request = CreateWebRequest(uri);
WebResponse response = request.GetResponse();
result = GetPageHtml(response);
...
private string GetPageHtml(WebResponse response) {
char[] buffer = new char[Buffer_Size];
Stream responseStream = response.GetResponseStream();
using(StreamReader reader = new StreamReader(responseStream)) {
int index = 0;
int readByte = 0;
do {
readByte = reader.Read(buffer, index, 256);
index += readByte;
}
while (readByte != 0);
response.Close();
}
string result = new string(buffer);
result = result.TrimEnd(new char[] {'\0'});
return result;
}
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;
}