Parsing POST request data with FiddlerCore - c#

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?

Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

Related

HTTPWebResponse "GET" API Call Exception - C#

I'm attempting to access a remote API and I'm getting a few exceptions during the HTTPWebResponse call. Below is my code:
//url
string responseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.someapi.com")
request.Method = "GET";
request.UseDefaultCredentials = true;
request.ContentType = "application/json; charset=utf-8";
request.Headers("x-ms-client-id", "data");
try{
using (var response = (HttpWebRequest)req.GetResponse()){ <--- this line is the one that fails. System.IO.IOException here.
using (var stream = response.GetResponseStream()){
using(var sr = new StreamReader(stream)){
responseValue = sr.ReadToEnd();
}
}
}
} catch ///catch
The errors I'm getting are SocketExceptions and WebExceptions. I'm not sure why this specific call is failing. When I attempt the same URL and headers in Postman, the call returns a 200.
Any ideas would be appreciated.
EDIT:
Adding the error messages I'm getting. The exception being thrown when the response is attempted is
System.IO.IOException: "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
Usually, I often use HttpWebRequest like below code.
You can download the HttpHelper I compiled and call it according to my reference example, or you can add Http Header as required.
How to invoke HttpHelper, ex: Get Method
Console app to use azure storage tableapi
String PostParam = String.Empty;
if (Data != null)
{
PostParam = Data.ToString();//Newtonsoft.Json.JsonConvert.SerializeObject(Data);
}
byte[] postData = Encoding.UTF8.GetBytes(PostParam);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url + (Id == null ? "" : '/' + Id.ToString())));
request.Method = Method;
request.ServicePoint.Expect100Continue = false;
request.Timeout = HttpRequestTimeOut;
request.ContentType = "application/json";
request.ContentLength = postData.Length;
if (postData.Length > 0)
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postData, 0, postData.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Response.Code = response.StatusCode;
using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
Response.Data = stream.ReadToEnd();
}
}

c# HttpWebRequest get response string

I'm trying to send some data through HTTPS Post without certification.
But I'm getting null however that response status code is OK.
Why is this? Any help would be greatly appreciated.
I want to receive "hello" string from https://test.com/post_test.php.
I saw many examples related to this, but none is working for me.
Does anyone know what I am missing?
Can some one guide me how to do that?
Thanks in advance!
c# code:
private static bool ValidateRemoteCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors policyErrors)
{
return true;
}
private String SendHttpWebPost(string strUrl, string strData)
{
string result = string.Empty;
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
Uri url = new Uri(strUrl);
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
request.Timeout = 5000;
// encoding
byte[] data = Encoding.UTF8.GetBytes(strData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
// send request
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Flush();
dataStream.Close();
// get response
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string strStatus = ((HttpWebResponse)response).StatusDescription;
StreamReader streamReader = new StreamReader(responseStream);
result = streamReader.ReadToEnd();
// close connection
streamReader.Close();
responseStream.Close();
response.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(SendHttpWebPost("https://test.com/post_test.php", "data=hello"));
}
php code:
<?php
echo($_REQUEST["data"]);
?>
Why don't you just simply request the Url without any fancy?
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(strUrl);
Request.Method = "GET";
Request.KeepAlive = true;
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
if (Response.StatusCode == HttpStatusCode.OK) {
....
}

c# How to send HTTP command as this - http://192.168.10.1/api/control?alert=101002

I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream getting this error

i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here

Json POST request to the server but server respond (400) Bad Request

I want to use google api for creation of gmail user account. I am sending JSON request to server for getting authorization code but I got these error in httpwebresponse :-
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com/o/oauth2/auth");
request.Method = "POST";
request.ContentType = "text/json";
request.KeepAlive = false;
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"scope\":\"https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile\"," + "\"state\":\"%2Fprofile\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"response_type\":\"code\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
//testdiv.InnerHtml = responsedata;
}
}
As soon as you get an exception, you have to read the actual responce from server there should be something helpfull. Like an error description or extended status code...
For Instance:
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
... your code goes here....
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
StreamReader sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}

Categories

Resources