So basically I want to get json string from specific url, and this json string is encrypted become a .txt file. All I want to do is get the encrypted string and decrypt it inside my application.
Here is my HttpWebRequest code to get the response string:
public string GetResponse(url)
{
string responseString = "";
HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
return responseString;
}
But what I get from the response is actually an unreadable string (only "O")
I already try to convert it to byte array before convert it to Base64 string, but still, the response string is not right.
Thanks for the help.
Unfortunately, i didnt realize that the response string actually includes added character "/0" which i have to remove it first, then i able to decrypt the string.
Thank you very much.
Related
So, I know how to get form data out by using Request.Form["abc"] however how would I go by getting the body out?
I've used this snippet in the below link:
https://gist.github.com/leggetter/769688
But, I'm not sure what to pass in as the Response.
In PHP to do this: file_get_contents('php://input'); and it's as simple as that.
Notes: The content type of the POST is application/json and the body contains the json string.
Thanks in advance.
If I understood your question correctly, here's what you could do when posting to a resource for which you expect a JSON response:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://foo.com/bar/");
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
//store json in a variable for later use
string json = readStream.ReadToEnd();
//make sure to close
response.Close();
readStream.Close();
Of course, this approach is synchronous; but, depending on your requirements, this might be just fine.
Since your question didn't specify whether you need to know how to parse the JSON itself, so I've left out an example of JSON parsing.
You'll need code similar to this to read the raw request body into a string variable.
using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
string text = reader.ReadToEnd();
}
I want to access a webpage & store the contents of the webpage into a database
this is the code I have tried for reading the contents of the webpage
public static WebClient wClient = new WebClient();
public static TextWriter textWriter;
public static String readFromLink()
{
string url = "http://www.ncedc.org/cgi-bin/catalog-search2.pl";
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = "POST";
System.Net.WebClient client = new System.Net.WebClient();
byte[] data = client.DownloadData(url);
string html = System.Text.Encoding.UTF8.GetString(data);
return html;
}
public static bool WriteTextFile(String fileName, String t)
{
try
{
textWriter = new StreamWriter(fileName);
}
catch (Exception)
{
return false;
Console.WriteLine("Data Save Unsuccessful: Could Not create File");
}
try
{
textWriter.WriteLine(t);
}
catch (Exception)
{
return false;
Console.WriteLine("Data Save UnSuccessful: Could Not Save Data");
}
textWriter.Close();
return true;
Console.WriteLine("Data Save Successful");
}
static void Main(string[] args)
{
String saveFile = "E:/test.txt";
String reSultString = readFromLink();
WriteTextFile(saveFile, reSultString);
Console.ReadKey();
}
but this code gives me an o/p as- This script should be referenced with a METHOD of POST. REQUEST_METHOD=GET
please tell me how to resolve this
You are mixing HttpWebRequest with System.Net.WebClient code. They are a different. You can use WebClient.UploadValues to send a POST with WebClient. You will also need to provide some POST data:
System.Net.WebClient client = new System.Net.WebClient();
NameValueCollection postData = new NameValueCollection();
postData.Add("format","ncread");
postData.Add("mintime","2002/01/01,00:00:00");
postData.Add("minmag","3.0");
postData.Add("etype","E");
postData.Add("outputloc","web");
postData.Add("searchlimit","100000");
byte[] data = client.UploadValues(url, "POST", postData);
string html = System.Text.Encoding.UTF8.GetString(data);
You can find out what parameters to pass by inspecting the POST message in Fiddler. And yes, as commented by #Chris Pitman, use File.WriteAllText(path, html);
I'm not sure if it's a fault on your side as I get the same message just by opening the page. The page source does not contain any html so I don't think you can do webRequest.Method = "POST". Have you spoken to the administrators of the site?
The .NET framework provides a rich set of methods to access data stored on the web. First you will have to include the right namespaces:
using System.Text;
using System.Net;
using System.IO;
The HttpWebRequest object allows us to create a request to the URL, and the WebResponse allows us to read the response to the request.
We’ll use a StreamReader object to read the response into a string variable.
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();
In this code sample, the URL variable should contain the URL that you want to get, and the result variable will contain the contents of the web page. You may want to add some error handling as well for a real application.
As far as I see, the URL you're requesting is a perl script. I think it demands POST to get search arguments and therefore delivers search results.
I have written a webservice which converts the XML Response of a TP-Open Service into JSON format. I am new to WCF and writing Webservice.
But the converted JSON format displays as follow.
"{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"25\", \"humidity\": \"48\", \"observation_time..
How to Remove these back slashes \ and my code so far.
public string checkweather(string q, string num_of_day)
{
HttpWebRequest request=..;
...
string Url = string.Format("http://free.worldweatheronline.com/feed/weather.ashx?q={0}&format={1}&num_of_days={2}&key={3}", q, format, num_of_days, key);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
Request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)Request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
var result2=reader.ReadToEnd();
}}}
return result2;
}
Please inform me if you need more information.
I think that your JSON is fine, the backslashes are escaping the quotations, which people have said. The following code shows some valid XML -> Json converting. (Using Json.NET)
const string xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
XmlDocument node = new XmlDocument();
node.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(node);
If you view in debug mode, you will see the backslashes, but the output is valid Json.
Output
{"note":{"to":"Tove","from":"Jani","heading":"Reminder","body":"Don't forget me this weekend!"}}
Are you sure there are backslashes in your string? It looks like me they are the escape characters because there are " characters in your string.
str = JToken.Parse(your string).ToString();
rest service time: System.Net.WebUtility.HtmlEncode(JsonString);
response time: System.Net.WebUtility.HtmlDecode(JsonString);
if your decoded code contains this string \\" then please replace \\ to \
I am trying to load an HttpWebResponse into an XmlDocument and am getting the exception "Data at the root level is invalid. Line 1, position 1". If I output the response to the Console I get "system.net.connectstream". The credentials don't seem to be my problem because if I enter an incorrect password my exception changes to the 404 error. Here is my code...
string username = "username";
string password = "password";
string url = "https://myurl.com";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(username, password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
Console.WriteLine(response.GetResponseStream());
xmlDoc.Load(response.GetResponseStream());
Thanks!
Calling ToString on GetResponseStream() isn't going to do much for you - Stream.ToString isn't overridden.
I suggest you use something like this for debugging::
// Prefer casting over "as" unless you're going to check it...
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
// For diagnostics, let's assume UTF-8
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Then replace the middle section (with StreamReader) with the XmlDocument.Load call.
I suspect you'll see that it's basically invalid XML, but the above should show you what it really is.
EDIT: Your comment shows the data as:
{"messages":{"message":"1 Device(s) returned."},"devices":{"device":
{"#id":"00","uuid":"00000000","phonenumber":"000000",
"user name":"0000","name":"Guy,Somebody","platform":"platform","os":"III",
"version":"1.1.1"}},"appName":"someApp"}
That's JSON. It's not XML. Don't try to load it as XML. You have two options:
Change what you're requesting so that you get an XML response back, if the server supports it
Parse it as JSON (e.g. with Json.NET) instead of as XML.
I am trying to make a POST request in which I am supposed to send Raw POST data.
Which property should I modify to achieve this.
Is it the HttpWebRequest.ContentType property. If, so what value should I assign to it.
public static string HttpPOST(string url, string querystring)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
try
{
requestWriter.Write(querystring);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
You want to set the ContentType property to the mime type of the data. If its a file, it depends on the type of file, if it's plain text then text/plain and if it's an arbitrary binary data of your own local purposes then application/octet-stream. In the case of text-based formats you'll want to include the charset along with the content type, e.g. "text/plain; charset=UTF-8".
You'll then want to call GetRequestStream() and write the data to the stream returned.