HTTPWebResponse returning no content - c#

Our company works with another company called iMatrix and they have an API for creating our own forms. They have confirmed that our request is hitting their servers but a response is supposed to come back in 1 of a few ways determined by a parameter. I'm getting a 200 OK response back but no content and a content-length of 0 in the response header.
here is the url:
https://secure4.office2office.com/designcenter/api/imx_api_call.asp
I'm using this class:
namespace WebSumit
{
public enum MethodType
{
POST = 0,
GET = 1
}
public class WebSumitter
{
public WebSumitter()
{
}
public string Submit(string URL, Dictionary<string, string> Parameters, MethodType Method)
{
StringBuilder _Content = new StringBuilder();
string _ParametersString = "";
// Prepare Parameters String
foreach (KeyValuePair<string, string> _Parameter in Parameters)
{
_ParametersString = _ParametersString + (_ParametersString != "" ? "&" : "") + string.Format("{0}={1}", _Parameter.Key, _Parameter.Value);
}
// Initialize Web Request
HttpWebRequest _Request = (HttpWebRequest)WebRequest.Create(URL);
// Request Method
_Request.Method = Method == MethodType.POST ? "POST" : (Method == MethodType.GET ? "GET" : "");
_Request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Win32)";
// Send Request
using (StreamWriter _Writer = new StreamWriter(_Request.GetRequestStream(), Encoding.UTF8))
{
_Writer.Write(_ParametersString);
}
// Initialize Web Response
HttpWebResponse _Response = (HttpWebResponse)_Request.GetResponse();
// Get Response
using (StreamReader _Reader = new StreamReader(_Response.GetResponseStream(), Encoding.UTF8))
{
_Content.Append(_Reader.ReadToEnd());
}
return _Content.ToString();
}
}
}
I cannot post the actual parameters because they are to the live system, but can you look at this code and see if there is anything that is missing?
Thanks!

Several obvious problems:
you're not URL-encoding your query parameters. If there are any spaces or special characters in your values, the server may barf on your input or truncate it.
you're trying to send data in the method body even if the method is GET -- this will fail. You need to stick values on the URL query string if it's a GET.
You're trying to roll your own version of WebClient instead of just using WebClient. Below is a WebClient sample which handles URL-encoding of parameters, handles GET and POST properly, etc.
.
public class WebSumitter
{
public string Submit(string URL, Dictionary<string, string> Parameters, MethodType Method)
{
// Prepare Parameters String
var values = new System.Collections.Specialized.NameValueCollection();
foreach (KeyValuePair<string, string> _Parameter in Parameters)
{
values.Add (_Parameter.Key, _Parameter.Value);
}
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; MSIE 6.0; Win32)";
if (Method == MethodType.GET)
{
UriBuilder _builder = new UriBuilder(URL);
if (values.Count > 0)
_builder.Query = ToQueryString (values);
string _stringResults = wc.DownloadString(_builder.Uri);
return _stringResults;
}
else if (Method == MethodType.POST)
{
byte[] _byteResults = wc.UploadValues (URL, "POST", values);
string _stringResults = Encoding.UTF8.GetString (_byteResults);
return _stringResults;
}
else
{
throw new NotSupportedException ("Unknown HTTP Method");
}
}
private string ToQueryString(System.Collections.Specialized.NameValueCollection nvc)
{
return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys,
key => string.Format("{0}={1}", System.Web.HttpUtility.UrlEncode(key), System.Web.HttpUtility.UrlEncode(nvc[key]))));
}
}

Use Fiddler to see whether any response is actually coming back across the network wire. It sounds like the server is sending you an empty 200 OK response.

Related

Two consecutive httpwebRequests in c#

Is it possible to make two consecutive web requests in c#? So make the inital request and then make a request from that response. I am doing this to fill out two consecutive forms in a c# program.
string postdata = "param1=...&param2=..."
var data1 = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data1.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data1, 0, data1.Length);
}
var response = (HttpWebResponse)request.GetResponse();
So if this is my first form how would I then go and fill out the second form that the completion of this form should lead to?
This is a (very) stripped down version of some code using HttpWebRequest that can send a request either via parameters or content but assumes either (or both) are objects passed in. E.g., if you need to send parameters like login and password usage would look like;
var response = HttpUtilities.Post("http://www.someurl.com/", new { login = "user", password = "1234");
// check response data + codes, etc...
var secondResponse = HttpUtilities.Post("http://www.someurl.com/page2", new { data = "stuff" });
The code below won't necessarily compile as I had to strip it down manually and is untested in its current form but it gives a very good idea of what's needed to check the response, debug, etc.;
namespace Helpers.Web
{
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Reflection;
using System.Web;
using Newtonsoft.Json;
using NLog;
public class HttpUtilities
{
#region NLog instance
/// <summary>
/// The single instance of an NLog LogManager for this class.
/// </summary>
private static Logger _logger = LogManager.GetCurrentClassLogger();
#endregion
#region Public Methods
public static TResponse Post<TResponse, TContent>(string uri, object parameters = null, TContent content = null)
where TContent : class
{
return GetResponse<TResponse, TContent>(uri, SerializeToQueryString(parameters),
content, HttpMethod.Post);
}
public static HttpWebResponse GetResponse<TContent>(string uri,
string parameters,
TContent content,
HttpMethod method)
where TContent : class
{
// build the full URL if parameters have been specified
if (!string.IsNullOrEmpty(parameters))
{
uri += "?" + parameters;
}
// make the request and send back the results
HttpWebRequest webRequest = BuildWebRequest(uri, content, method);
return GetWebResponse(uri, webRequest);
}
#endregion
#region Private Methods
private static HttpWebRequest BuildWebRequest<TContent>(string uri, TContent content, HttpMethod method)
where TContent : class
{
// get the request details
_logger.Trace("Building request for [{0}]", uri);
// set the web request details
_logger.Trace("Setting request header details...");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = method.ToString();
webRequest.ContentType = "application/json";
webRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
// do we have content to insert
string serializedContent = string.Empty;
if (content != null)
{
JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
// ignore the self referencing nature of EntityFramework objects and skip
// over the self references when serializing
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// serialize the object as json and convert it into bytes we can
// inject into the content stream of the request.
serializedContent = JsonConvert.SerializeObject(content, jsonSettings);
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteContent = encoding.GetBytes(serializedContent);
webRequest.ContentLength = byteContent.Length;
// write the content
// NOTE: the act of writing out the data actually sends the request!
_logger.Trace("Sending request and getting response from [{0}]", uri);
using (var contentStream = webRequest.GetRequestStream())
{
contentStream.Write(byteContent, 0, byteContent.Length);
}
_logger.Trace("Injected content into request to [{0}]. Content: {1}", uri, serializedContent);
}
else
{
// if there's no content then we haven't actually sent the request yet. However we still
// need to set the header details.
webRequest.ContentLength = 0;
_logger.Trace("Sending request and getting response from [{0}]", uri);
}
return webRequest;
}
private static HttpWebResponse GetWebResponse(string uri, HttpWebRequest webRequest)
{
HttpWebResponse response;
try
{
_logger.Debug("Sending [{0}] request to [{1}]...", webRequest.Method, webRequest.RequestUri.AbsoluteUri);
response = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException wex)
{
// we might still have response information on the request
// if this is so, then extract it and log it as we'll need to
// find out what the server actually replied with in order to debug
// what went on
_logger.Error(wex, "There was a problem getting a response from the server");
if (wex.Response != null)
{
try
{
// NOTE: this can be caused by the server returning a YSOD. You can see the formatted result
// in debug mode by using the HTML visualizer when looking at the content of the
// wResponseContent variable.
_logger.Debug("Attempting to extract server response details from WebException...");
using (Stream wResponseStream = wex.Response.GetResponseStream())
{
if (wResponseStream != null)
{
using (StreamReader wStreamReader = new StreamReader(wResponseStream))
{
string wResponseContent = wStreamReader.ReadToEnd();
_logger.Debug(wex, "Received fault response from [{0}]. Response: {1}",
uri, wResponseContent);
}
}
}
}
catch (Exception eex)
{
// there was an issue trying to get the response content from the original error.
// There's nothing more we can do except log this exception and rethrow the
// original.
_logger.Fatal(eex, "There was a problem getting response details from a WebException raised from the server");
throw;
}
}
else
{
_logger.Debug("No response data present in the exception.");
}
throw;
}
catch (Exception ex)
{
_logger.Error(ex, "There was a problem getting a response from [{0}]", uri);
throw;
}
return response;
}
private static string SerializeToQueryString(object parameters)
{
// if we weren't given anything then there's nothing we can do
if (parameters == null)
{
return string.Empty;
}
if (parameters is string)
{
return parameters as string;
}
// iterate over the parameter properties and build the query string
Type type = parameters.GetType();
BindingFlags flags = BindingFlags.Instance
| BindingFlags.GetProperty
| BindingFlags.Public;
if (type.IsInterface)
{
// if the type is an interface, only get the interface's members
flags |= BindingFlags.FlattenHierarchy;
}
PropertyInfo[] properties = type.GetProperties(flags);
List<string> urlParameters = new List<string>();
foreach (PropertyInfo prop in properties)
{
// convert the value to a string first so that we can make it safe
// to put into the URL
_logger.Trace("Getting value from {0}.{1} [{2}]", type.FullName, prop.Name, prop.PropertyType.FullName);
object rawValue = prop.GetValue(parameters, null);
string propertyValue = string.Empty;
if (rawValue != null)
{
propertyValue = rawValue.ToString();
}
urlParameters.Add(string.Format("{0}={1}", prop.Name, HttpUtility.UrlEncode(propertyValue)));
}
return string.Join("&", urlParameters.ToArray());
}
#endregion
}
}

Unable to Post on Pinterest using their API

I'm receiving a 400 Bad Request error message when posting a pin on Pinterest. It works using Postman, but doesn't work programmatically. Using C#, has anyone been able to successfully post a pin on Pinterest without using the pinsharp wrapper?
private void postPinterest(string messages, string id, string usertoken, string image, string boardname, string username)
{
string link = null;
boardname = boardname.Replace(" ", "-");
string board = username + "/" + boardname;
string url = "https://api.pinterest.com/v1/pins?access_token=" + usertoken;
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(board))
sb.Append("&board=" + HttpUtility.UrlEncode(board));
if (!string.IsNullOrEmpty(messages))
sb.Append("&note=" + HttpUtility.UrlEncode(messages));
if (!string.IsNullOrEmpty(link))
sb.Append("&image_url=" + HttpUtility.UrlEncode(link));
string postdata = sb.ToString().Substring(1);
PostData(url, postdata);
}
private object PostData(string url, string postdata)
{
object json=null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.Accept = "application/json";
using (var stream = req.GetRequestStream())
{
byte[] bindata = Encoding.ASCII.GetBytes(postdata);
stream.Write(bindata, 0, bindata.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string response = new StreamReader(resp.GetResponseStream()).ReadToEnd();
json = JsonConvert.DeserializeObject<dynamic>(response);
return json;
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
return json;
}
}
}
}
return json;
}
EDIT:
It doesn't work using the JSON format or x-www-form-urlencoded format.
I changed the content type to application/x-www-form-urlencoded and now I'm receiving the error message below. I receive 400 Bad Request error using JSON format:
"{\n \"message\": \"405: Method Not Allowed\",\n \"type\": \"http\"\n}"
The problem is the the parameter that you are posting.
In the Api i could find board as a parameter but both note and image comes under field parameter which specifies the return type JSON.
As per documentation on this page you can post in this format
https://api.pinterest.com/v1/boards/anapinskywalker/wanderlust/pins/?
access_token=abcde&
limit=2&
fields=id,link,counts,note
So I tried the following and its getting response
https://api.pinterest.com/v1/boards/?access_token="YourTokenWithoutQuotes"&fields=id%2Ccreator
Would suggest you to first test the Api you are hitting putting a breakpoint inside the PostData function and check if the passed url is in the correct format and compare it with Pininterest API Explorer.
As you might have already received authorization code and access token so I am assuming your post function should be working fine.
public string postPinterest(string access_token,string boardname,string note,string image_url)
{
public string pinSharesEndPoint = "https://api.pinterest.com/v1/pins/?access_token={0}";
var requestUrl = String.Format(pinSharesEndPoint, accessToken);
var message = new
{
board = boardname,
note = note,
image_url = image_url
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response;
}

Retrieve all instances of recurring event via CSOM

I need to get all the instances of a recurring calendar event in Sharepoint 2013 online via CSOM. I read that it can't be done, that I need to do it via REST API directly.
My question:
1) Is it possible to get the items from a View instead of from a List, because the calendar comes with a default view where I can see all instances of the recurring event
2) I have an example of retrieveing data via REST un C# that's working fine, but I can't seem to add a Caml Query to it (in C#)
here's my non-working code:
HttpWebRequest itemRequest =
(HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists/getbytitle('" + listName + "')/Items");
itemRequest.Method = "POST";
itemRequest.Accept = "application/atom+xml";
itemRequest.ContentType = "application/atom+xml;type=entry";
itemRequest.Headers.Add("Authorization", "Bearer " + accessToken);
using (var writer = new StreamWriter(itemRequest.GetRequestStream()))
{
writer.Write(#"{ 'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml': '<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>little test</Value></Eq></Where></Query></View>' } }");
}
HttpWebResponse itemResponse = (HttpWebResponse)itemRequest.GetResponse();
I get 500 Internal server error
Any thoughts??
thank you
I would recommend to utilize Fiddler to inspect REST SharePoint RESTfull web service requests.
In your case the endpoint is not correct. Since you need to request list items via CAML query, replace endpoint url from:
/_api/Web/lists/getbytitle('" + listName + "')/Items
to this one:
/_api/Web/lists/getbytitle('" + listName + "')/getitems
Secondly, application/atom+xml;type=entry HTTP Content-Type header is not supported in POST requests (see the list of supported MIME types below). So, replace the lines:
itemRequest.Accept = "application/atom+xml";
itemRequest.ContentType = "application/atom+xml;type=entry";
for example, with these ones:
itemRequest.Accept = "application/json";
itemRequest.ContentType = "application/json";
That's it.
The list of supported MIME types
application/json;odata=minimalmetadata;streaming=true
application/json;odata=minimalmetadata;streaming=false
application/json;odata=minimalmetadata
application/json;odata=fullmetadata;streaming=true
application/json;odata=fullmetadata;streaming=false
application/json;odata=fullmetadata
application/json;odata=nometadata;streaming=true
application/json;odata=nometadata;streaming=false
application/json;odata=nometadata
application/json;streaming=true
application/json;streaming=false
application/json;odata=verbose
application/json
You could also utilize the following class for performing REST requests:
public class SPRestExecutor
{
public SPRestExecutor(Uri webUri,string accessToken)
{
WebUri = webUri;
AccessToken = accessToken;
}
public JObject ExecuteJsonWithDigest(string endpointUrl, HttpMethod method, IDictionary<string, string> headers, JObject payload)
{
var formDigestValue = RequestFormDigest();
var finalHeaders = new Dictionary<string, string>();
if (headers != null)
{
foreach (var key in headers.Keys)
{
finalHeaders.Add(key, headers[key]);
}
}
finalHeaders.Add("X-RequestDigest", formDigestValue);
var result = ExecuteJson(endpointUrl, method, finalHeaders, payload);
return result;
}
public JObject ExecuteJson(string endpointUrl, HttpMethod method, IDictionary<string, string> headers, JObject payload)
{
var request = (HttpWebRequest)WebRequest.Create(WebUri.ToString() + endpointUrl);
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AccessToken);
request.Method = method.Method;
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json;odata=verbose";
if (payload != null)
{
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(payload);
writer.Flush();
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using(var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
return JObject.Parse(result);
}
}
}
}
/// <summary>
/// Request Form Digest
/// </summary>
/// <returns></returns>
protected string RequestFormDigest()
{
var result = ExecuteJson("/_api/contextinfo", HttpMethod.Post, null, null);
return result["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
}
public string AccessToken { get; private set; }
public Uri WebUri { get; private set; }
}
Gist
Usage
var client = new SPRestExecutor(webUri,accessToken);
var payload = JObject.Parse(#"{ 'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml': '<View><Query/></View>' } }");
var data = client.ExecuteJson("/_api/web/lists/getbytitle('Documents')/getitems", HttpMethod.Post, null, payload);
Thank you Vadim Gremyachev, your post got me on track.
I had 3 problems, the first one was calling "Items" instead of "getItems", and the second one was using "application/atom+xml;type=entry" as a ContentType (just as Vadim stated).
The third and last problem, was using simple quotes all over the query. Inside the ViewXml, I used scaped double quotes so they were not confused with the one closing the ViewXml element.
So, the working code ended up being like this:
byte[] data = new ASCIIEncoding().GetBytes("{ 'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml': '<View><Query><Where><Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">little test</Value></Eq></Where></Query></View>' } }");
HttpWebRequest itemRequest =
(HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists/getbytitle('" + listName + "')/getitems");
itemRequest.Method = "POST";
itemRequest.ContentType = "application/json; odata=verbose";
itemRequest.Accept = "application/atom+xml";
itemRequest.Headers.Add("Authorization", "Bearer " + accessToken);
itemRequest.ContentLength = data.Length;
Stream myStream = itemRequest.GetRequestStream();
myStream.Write(data, 0, data.Length);
myStream.Close();
HttpWebResponse itemResponse = (HttpWebResponse)itemRequest.GetResponse();

Sending data to php from windows phone

I need to send some data from windows phone 7 to php page through POST method, I have the following code at wp7 side
public void SendPost()
{
var url = "http://localhost/HelpFello/profile.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
MessageBox.Show("data sent");
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "user_id=3&name=danish&email_id=mdsiddiquiufo&password=12345&phone_Number=0213&about_me=IRuel2&rating=5";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
}
and following on my localhost, to send the data to database
<?php
require_once("constants.php");
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$email_id = $_POST['email_id'];
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
$about_me = $_POST['about_me'];
$rating = $_POST['rating'];
$query="INSERT INTO profile(User_ID,Name,Email_ID,password,Phone_Number,About_Me,Rating) VALUES ({$user_id},'{$name}','{$email_id}','{$password}',{$phone_number}, '{$about_me}' , {$rating})";
mysql_query($query,$connection);
mysql_close($connection);
?>
When I run the code I have no errors it means code is working fine, but no data is inserted in the database.
I think there is a better way than HttpWebRequest. That is WebClient. You can change the method there and append data like you do in get string. key=value&key2=value then when you invoke that request and get the response try debugging and getting the output from VS or if that is difficult simply assign he string to a textblock in the code. You will get to know if that page has been ever executed or not.
A sample code :
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
Parameters prms = new Parameters();
prms.AddPair("email", email);
prms.AddPair("password", password);
wc.UploadStringAsync(new Uri(loginUrl), "POST", prms.FormPostData(), null);
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// e.Result will contain the page's output
}
// This is my Parameters and Parameter Object classes
public class Parameters
{
public List<ParameterObject> prms;
public Parameters()
{
prms = new List<ParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new ParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class ParameterObject
{
public string id;
public string value;
public ParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
First error: assuming that no error messages means success
Second error: gaping SQL injection holes
first fix: always assume queries will fail, and check for that condition:
$result = mysql_query($query) or die(mysql_error());
second fix: ditch the mysql_() functions and switch to PDO using prepared statements with placeholders. Boom. No more injection problems, and your code won't stop working on you when mysql_() is removed in a future PHP version.
ps..
3rd error: no quotes on your phone number value. So someone submits 867-5309, and you end up inserting -4442 because mysql saw it as two numbers being subtracted, not a string.

How to make an HTTP get request with parameters

Is it possible to pass parameters with an HTTP get request? If so, how should I then do it? I have found an HTTP post requst (link). In that example the string postData is sent to a webserver. I would like to do the same using get instead. Google found this example on HTTP get here. However no parameters are sent to the web server.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
GET request with multiple params:
curl --request GET --url
http://localhost:8080/todos/?limit=10&offset=2 --header
'content-type:application/json'
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value in URL

Categories