Saving a HTML path to a file - c#

Edited my code to use WebClient...still doesnt work
string hhtmlurl = /Thumbnail.aspx?productID=23&Firstname=jimmy&lastnight=smith;
string strFileName = string.Format("{0}_{1}", hfUserID.Value, Request.QueryString["pid"].ToString() + documentID.ToString());
WebClient client = new WebClient();
client.DownloadFile("http://www.url.ca/" + hhtmlurl.Value + "card=1", strFileName);

Try this method. This will give you string return for the entire html content. Write this string in whatever file you want
public string GetHtmlPageContent(string url)
{
HttpWebResponse siteResponse = null;
HttpWebRequest siteRequest = null;
string content= string.Empty;
try
{
Uri uri = new Uri(url);
siteRequest = (HttpWebRequest)HttpWebRequest.Create(url);
siteResponse = (HttpWebResponse)siteRequest.GetResponse();
content = GetResponseText(siteResponse);
}
catch (WebException we)
{
// Log error
}
catch (Exception e2)
{
// Log error
}
return content;
}
public string GetResponseText(HttpWebResponse response)
{
string responseText = string.Empty;
if (response == null)
return string.Empty;
try
{
StreamReader responseReader = new StreamReader(response.GetResponseStream());
responseText = responseReader.ReadToEnd();
responseReader.Close();
}
catch (Exception ex)
{
// Log error
}
return responseText;
}
Hope this will help you.

WebClient.DownloadFile would probably be easier.

Instead of FileStream, use the WebClient class, which offers the delightfully simple DownloadFile() method:
WebClient client = new WebClient();
client.Downloadfile("http://www.url.ca/" + hhtmlurl + "card=1", strFileName);

Related

How to create issue in jira using c#

I'm trying to create an issue in JIRA cloud using c# and the REST API,
I get the 400 error (bad rquest), I dont know what I'm doing wrong !
This is My functions
public static string PostJsonRequest(string endpoint, string userid, string password, string json)
{
// Create string to hold JSON response
string jsonResponse = string.Empty;
using (var client = new WebClient())
{
try
{
client.Encoding = System.Text.Encoding.UTF8;
client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password));
client.Headers.Add("Content-Type: application/json");
client.Headers.Add("Accept", "application/json");
var uri = new Uri(endpoint);
var response = client.UploadString(uri, "POST", json);
jsonResponse = response;
}
catch (WebException ex)
{
// Http Error
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
var statusCode = (int)wrsp.StatusCode;
var msg = wrsp.StatusDescription;
// throw new SmtpException(statusCode, msg);
}
else
{
// throw new HttpException(500, ex.Message);
}
}
}
return jsonResponse;
}
And this is my JSON
string json = #"{
'fields':
{
'project':
{
'key':'IS'
},
'summary':'REST Test',
'issuetype':
{
'name':'Bug'
},
}
}";
string Url = "https://XXXXXX.atlassian.net/rest/api/2/issue/";
Any Ideas on what I'm doing wrong ?

API Call not successful

Good day Guys,
I am trying to Use an SMS API. Everything looks fine from my end but the SMS is not delivering. If i use the URL directly on Browser, it executes.
Or is anything wrong with how i built the string?
Below is the code.
Please Note tht cbo.Title is a comobox, txtFirstname is a Textbox.
public void NewText()
{
string username = "something#gmail.com";
string password = "Password";
string urlStr;
string message=" Dear " + cbo_Title.Text + " " + txt_FirstName.Text + ", Your New Savings Account Number is " + Account_No + ".Welcome to AGENTKUNLE Global Services. Your Future is Our Priority ";
string sender = "AGENTKUNLE";
string recipient=txt_Phone.Text;
urlStr = "https://portal.nigeriabulksms.com/api/?username="+username+"+password="+password+"+sender="+sender+"+message="+message+"+ mobiles="+recipient;
Uri success = new Uri(urlStr);
}
private string SendSms(string apiUrl)
{
var targetUri = new Uri(apiUrl);
var webRequest = (HttpWebRequest) WebRequest.Create(targetUri);
webRequest.Method = WebRequestMethods.Http.Get;
try
{
string webResponse;
using (var getresponse = (HttpWebResponse) webRequest.GetResponse())
{
var stream = getresponse.GetResponseStream();
if (stream != null)
using (var reader = new StreamReader(stream))
{
webResponse = reader.ReadToEnd();
reader.Close();
}
else
webResponse = null;
getresponse.Close();
}
if (!string.IsNullOrEmpty(webResponse?.Trim()))
return webResponse.Trim();
}
catch (WebException ex)
{
ErrorHelper.Log(ex);
}
catch (Exception ex)
{
ErrorHelper.Log(ex);
}
finally
{
webRequest.Abort();
}
return null;
}
You never make a request.
The Uri object is just a container for the uri (see Microsoft Docs).
Check out the HttpClient class if you want to send a request.

Attempting to post XML file to MVC RESTful API and de-serialize into c# class

The front end seems to post fine and my routing seems to be working as my API seems to get the request and the filename is valid. However, when I attempt await request.Content.ReadAsStreamAsync(); it doesn't seem to read anything and I get a
Data at the root level is invalid. Line 1, position 1.
exception when de-serializing...
Been at this for awhile trying the different solutions available with no success.. please help.
Things I've tried:
Different content-types
Different webclient methods to upload (uploadstring, uploadfile, uploaddata)
Using WebRequest instead of webclient (I will consistently get an unsupported media type message as a response)
My code:
public string CreateJob()
{
string test = "";
string sURL = "http://" + _domain + _apiRoot + "CreateJob/OrderXML";
try
{
var ms = new MemoryStream();
using (FileStream src = System.IO.File.Open(#"C:\XML\PageDNAOrderXML.txt", FileMode.Open))
{
src.CopyTo(ms);
}
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "text/xml";
wc.Headers[HttpRequestHeader.AcceptEncoding] = "Encoding.UTF8";
//wc.Headers[HttpRequestHeader.ContentLength] = ms.Length.ToString();
wc.UploadString(sURL, ms.ToString());
}
}
catch (Exception ex)
{
test = ex.Message;
}
return test;
}
RESTful API
[System.Web.Http.HttpPost]
public async void CreateJob(string filename)
{
string success = "false";
try
{
//XDocument doc = XDocument.Load
XmlSerializer xmls = new XmlSerializer(typeof(PdnaXmlParse));
Stream reqStream = await Request.Content.ReadAsStreamAsync();
PdnaXmlParse res = (PdnaXmlParse)xmls.Deserialize(new XmlTextReader(reqStream));
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}

How to send and retrieve data from asp by using the HttpURLConnection in Android?

I have a login process in android, a user account information in a database and a aspx file which can check whether the username and password is correct or not.
In my aspx.cs file, I have a process method to check the username and password like this:
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
System.Web.SessionState.HttpSessionState session = context.Session;
string result = "";
try
{
string action = request.Form["action"].ToString();
switch (action)
{
//Login test
case "login":
result = this.login(session, request);
break;
}
}
catch (Exception e)
{
result = "{\"message\":\"" + e.Message + "\"}";
}
response.Clear();
response.ContentType = "application/json;charset=UTF-8;";
response.Write(result);
response.End();
}
#region Login test
private string login(System.Web.SessionState.HttpSessionState session, HttpRequest request)
{
LoginSample sample = new LoginSample();
JsonObject jo = new JsonObject();
string username = request.Form["username"];
string password = request.Form["password"];
bool login = sample.Login(username, password);
if (login)
jo.Add("msg", "success");
else
jo.Add("msg", "failed");
return jo.ToString();
}
And my class to pass the username and password to C# INCOMPLETE:
public static String excutePost(String vUserName, String vPassword)
{
try {
URL url = new URL("localhost:60068/SampleLogin.aspx");
String urlParameters="param1=" + URLEncoder.encode(vUserName,"UTF-8")+
"&param2="+URLEncoder.encode(vPassword,"UTF-8");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(urlParameters.getBytes().length);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(urlParameters);
dataOutputStream.flush();
dataOutputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while((line = bufferedReader.readLine()) != null)
{
response.append(line);
response.append('\r');
}
bufferedReader.close();
return response.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
How can I pass the parameters to the aspx.cs file and process and return a boolean back to android? Please help.
Check your Http response code value after write data to outputstream.
//Write Data
StringBuilder builder = new StringBuilder();
builder.append(conn.getResponseCode())
.append(" ")
.append(conn.getResponseMessage())
.append("\n");
// Read response data

Problems with a REST request in windows phone 8 using C#

I am trying to access to some rest services of a specific web server for my WP8 app and I canĀ“t do it well. For example, this is the code that I use when I try to login the user. I have to pass a string that represents a Json object ("parameters") with the username and the password and the response will be a json object too. I can't find the way to pass this pasameters in the rest request.
This is the code;
public void login(string user, string passwrd)
{
mLoginData.setUserName(user);
mLoginData.setPasswd(passwrd);
string serviceURL = mBaseURL + "/service/user/login/";
string parameters = "{\"username\":\"" + mLoginData.getUserName() + "\",\"password\":\"" + mLoginData.getPasswd() + "\"}";
//MessageBox.Show(parameters);
//MessageBox.Show(serviceURL);
//build the REST request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL);
request.ContentType = "application/json";
request.Method = "POST";
//async request launchs "Gotresponse(...) when it has finished.
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
private void GotResponse(IAsyncResult ar)
{
try
{
string data;
// State of request is asynchronous
HttpWebRequest myHttpWebRequest = (HttpWebRequest)ar.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(ar))
{
// Read the response into a Stream object.
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
}
catch (Exception e)
{
string exception = e.ToString();
throw;
}
}
I tried too with the webClient and the httpClient classes too but without any result.
Thanks and sorry for my bad english.
I solved it with the HttpClient class. This is the code.
public async void login(string user, string passwrd)
{
string serviceURL = "";
string parameters = "";
HttpClient restClient = new HttpClient();
restClient.BaseAddress = new Uri(mBaseURL);
restClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, serviceURL);
req.Content = new StringContent(parameters, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
string responseBodyAsText = "";
try
{
response = await restClient.SendAsync(req);
response.EnsureSuccessStatusCode();
responseBodyAsText = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
string ex = e.Message;
}
if (response.IsSuccessStatusCode==true)
{
dynamic data = JObject.Parse(responseBodyAsText);
}
else
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
MessageBox.Show("User or password were incorrect");
}
else
{
MessageBox.Show("NNetwork connection error");
}
}
}
I wasn't setting the header values of the request correctly.
I hope this can help someone.

Categories