How to do httpPost to a webservice which accepts a byte array of a file using c# - asp.net

I am working on an API kind of project,
I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)
public UploadFileImage(string employeeId, byte[] imageBytes, string imageName)
{
// saves the imagebyte as an image to a folder
}
the web service would be consumed by a web app, or windows or even iphone or such portable stuffs. I am testing my web service using a web app, by simple httpPost.
string Post(Uri RequestUri, string Data)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(RequestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = IsXml.Checked ? "text/xml" : "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(Data);
Stream os = null; // send the Post
request.ContentLength = bytes.Length; //Count bytes to send
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
return streamReader.ReadToEnd();
}
catch (Exception ex)
{
return ex.Message;
}
}
This code works fine for evey method like, AddEmployee, DeleteEmployee etc. THe parameter Data is of form "Id=123&name=abcdefgh&desig=Developer",
How I call any other function is
Post(new Uri("http://localhost/addemployee"),"name=abcd&password=efgh")
where post is the function i wrote.
All good for all functions. Except that I dont know how to consume the above mentioned function UploadFileImage to upload an image?
Thanks

Try encoding the imageBytes as Base64.

From your code snippet is not too clear how you call UploadFileImage, that is how you convert its parameters tripplet into Data.
That is why my answer is quite generic:
In general, you'd better transfer your image file by
request.ContentType = "multipart/form-data; boundary=----------------------------" + DateTime.Now.Ticks.ToString("x");
Please allow me to refer you to a sample at StackOverflow on how to format a multipart request. I am sure that if you google, you shall find a lots of detailed examples and explanations as well.
I hope this helps :-)

Related

How to call a WebService which has a querystring data?

I have a webservice which i need to call in .net application. The link looks like this.
http://www.contoso.com/student?id=12345
This will work only when its called like this. For rest of the this i dont have access. ie if i call it on a browser without the querystring it will not work. but with querystring it will return an XML data.
Now, when i call this in the .net application its not working?
How can I call this in a .NET application?
The Normal Webservice Importing methods are not working since it needs a querystring with value and we dont have access to the links which doesnt have the querystring.
How are you currently trying to download it?
A very simple way to do this is to use the HttpWebRequest and HttpWebResponse classes;
public XmlDocument GetStudentXml(int studentId)
{
XmlDocument targetXml = new XmlDocument();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://www.contoso.com/student?id={0}", studentId));
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (Stream responseStream = webResponse.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(responseStream);
targetXml.Load(reader);
reader.Close();
}
webResponse.Close();
return targetXml;
}
This method simply creates a HttpWebRequest, initializes it with the URL (via String.Format so as to append the student id), some windows credentials and the expected content type.
It then calls the remote address via the GetResponse method. The response is then loaded into a stream, and an XmlTextReader is used to load the Xml data from the response stream into the XmlDocument, which is then returned to the caller.
You can also use WebClient and XDocument to achieve the same thing:
string url = String.Format("http://www.contoso.com/student?id={0}", studentId);
string remoteXml;
using (var webClient = new WebClient())
{
remoteXml = webClient.DownloadString(url);
}
XDocument doc = XDocument.Parse(remoteXml);

Unable to Pass Image in HTTP POST in a HTTP Web Request in ASP.NET

I am having trouble converting an image into bytes and saving it in database.
Here is the description,
I have an image that will be send from a remote device to the web server using HTTP POST.
so what I am doing is I ask them to sent the image to me.
Since the data is sent in POST i assume they will send me the Bytes by converting the bytes into string using
byte[] img = FileUpload1.FileBytes;
Encoding enc = Encoding.ASCII;
string img = enc.GetString(img);
Then they make a WebRequest using HTTPWebRequest and append this image in HTTP POST.
The Whole Code for making the request ---
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
//Create the POST Data
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
imgByte = imgUpload.FileBytes;
}
string imgPh = null;
Encoding enc = Encoding.ASCII;
if (imgByte != null)
{
imgPh = enc.GetString(imgByte);
}
string postData = "sid=8062BD53EB4552AD6D0FBB7E5DC5B7AF&status=Y&uid=123456789012&fname=Dinesh Singh&lname=Malik&ftname=Balwan&yrbirth=1988&gender=Male&address1=Address1&address2=Address2&address3=Address3&address4=Address4&imagePh=" + imgPh;
byte[] post = Encoding.UTF8.GetBytes(postData);
//Set the Content Type
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
// Write the data to the request stream.
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
// Get the response.
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
On the Page to which Request is made I am getting this image again into bytes using
Encoding enc = Encoding.ASCII;
byte[] imagePhoto = enc.GetBytes(postData["imageph"]);
From Here I save it into my Database
But when I retrieve the image using the Handler, it does not show the image.
The issue is the conversion of the image from byte[] to string and then converting string into byte[] at the Web Server. (Because when I save the image directly without this conversion using TestPage on server it shows the image.)
So What am I doing wrong in this.
Also is there any way in the above code to get the data of HTTP Post as received by the Web Server (retrieve HTTP Headers).
I want to retrieve this data received to sent it back to the Other Development to develop the request at the device in the same format as I am receiving in the HTTP Web Request URL
Any help would be appreciated.
Ok I think finally I figured it out.
What I did was -
Image -> byte[] -> Convert.ToBase64String -> Append The String Data to Post Request
At the Server-
Get the Post Data -> Convert.FromBase64String -> byte[] -> Insert into Database
Works Great...:)
Thanks

User authentication through REST web service on a different domain - asp.net

I am looking to connect to a web service on a different domain in order to authenticate users. The Web Service itself is a RESTful service, written in Java. Data is passed to and from it in JSON.
I initially tried to connect using jQuery (see below)
function Login()
{
$.ajax({
url: "http://www.externaldomain.com/login/authenticate",
type: "POST",
dataType: "json",
contentType: "application/json",
data: "{'emailAddress':'bob#bob.com', 'password':'Password1'}",
success: LoadUsersSuccess,
error: LoadUsersError
});
}
function LoadUsersSuccess(){
alert(1);
}
function LoadUsersError(){
alert(2);
}
However, when checking on Firebug, this brought up a 405 Method Not Allowed error.
At this stage, as this is the first time I've really worked with web services, I really just wondered whether this was the best way to do things? Is it worth persevering with this method in order to find a solution, or am I best to maybe try and find a server-side answer to this issue? If so, does anyone have any examples they could post up?
Many thanks
Doing cross-domain web service calls in a browser is very tricky. Because it's a potential security vulnerability, browsers block these types of requests. However, there is a workaround called JSONP. If you use JSONP instead of plain JSON, you should be able to make the cross-domain request.
Right ok, to update where I am, I checked in firebug and on the external server and the reason why I'm getting a 405 error is because I'm doing a Get rather than a Post.
What I need to do is send the username and password, then receive a GUID back which will then be used for any future requests. I thought by having 'type:post' in the code would be enough but apparently not. Anyone know where I might be going wrong here? As I said, a novice to web services and nothing I have tried from looking online has had any effect. Many thanks
Ok, I got the problem solved, and I did it by going back to C# and doing it there instead of using jQuery or JSONP and I used Json.Net for handling the data received. Here is the code:
protected void uxLogin_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder();
data.Append("{");
data.Append("'emailAddress': '" + uxEmail.Text + "', ");
data.Append("'password': '" + uxPassword.Text + "'");
data.Append("}");
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
string url = System.Configuration.ConfigurationManager.AppSettings["AuthenticationURL"].ToString();
string JSONCallback = string.Empty;
Uri address = new Uri(url);
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";
// Create a byte array of the data we want to send
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
JSONCallback = reader.ReadToEnd().ToString();
}
if (!String.IsNullOrEmpty(JSONCallback))
{
JObject jObject = JObject.Parse(JSONCallback);
if ((bool)jObject["loginResult"] == false)
{
string errorMessage = jObject["errorMessage"].ToString();
int errorCode = (int)jObject["errorCode"];
}
else
{
string idToken = jObject["idToken"].ToString();
Session["Userid"] = idToken;
Response.Redirect("~/MyDetails.aspx");
}
}
else
{
uxReturnData.Text = "The web service request was not successful - no data was returned";
}
}
Thanks anyway :)

How to send a xml file over HTTP and HTTPS protocol and get result back

i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};

How do I make a simple post to Twitter via ASP.NET (VB, preferably)?

I don't want to do anything fancy on Twitter except post to it via my site once a day. I have searched around a bit and there are all sorts of super-complex ways to do every little thing that Twitter does, but there seems to be little documentation on how to do the simplest thing, which is make a post!
Does anyone know how to do this? Or can you at least point me in the right direction? I don't need full wrappers or anything (http://apiwiki.twitter.com/Libraries#C/NET), just one simple function that will post to Twitter.
Thanks!
This is the easiest implementation ever. Up and running in under 2 minutes: Twitterizer
Its fairly simple; you just need to post an xml file to a web page using webrequest.create. This example is close (assumes you have the xml for the message in another place and just pass it into twitterxml variable as a string. The url might not be the right one; found it on this [page][1] which defines the interface
WebRequest req = null;
WebResponse rsp = null;
try
{
string twitterXML = "xml as string";
string uri = "http://twitter.com/statuses/update.format";
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(twitterXML);
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
}
[1]: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses update
There are a couple different ways of doing this, they vary depending on the tools you want to use and have access to. Option 1 will work right out of the box, but the coding can be complicated. Option 3 you will have to download tools for, but once there installed and loaded you should be able to consume the twitter api very quickly.
Use WebRequest.Create to create/send messages to remote endpoints
Use WCF, create a mirror endpoint and access the twitter api using client only endpoint.
Use the WCF REST Starter Kit Preview 2, which has a new class called the HttpClient. I would have to recommend this technique if you can. Here is a great video Consuming a REST Twitter Feed in under 3 minutes.
Here is a sample of using the WCF REST Starter Kit's HttpClient:
public void CreateFriendship(string friend)
{
using (var client = new HttpClient())
{
var url = string.Format("http://www.twitter.com/friendships/create/{0}.xml?follow=true", friend);
client.Post(url)
.CheckForTwitterError()
.EnsureStatusIs(HttpStatusCode.OK);
}
}
Add a comment if you'd like more info about a particular method.
Update:
For Option #1 see this question: Remote HTTP Post with C#
There are a few ways of doing this, you can check out http://restfor.me/twitter and it will give you the code from RESTful documentation.
Essentially making any authenticated call you can follow this logic:
///
/// Executes an HTTP POST command and retrives the information.
/// This function will automatically include a "source" parameter if the "Source" property is set.
///
/// The URL to perform the POST operation
/// The username to use with the request
/// The password to use with the request
/// The data to post
/// The response of the request, or null if we got 404 or nothing.
protected string ExecutePostCommand(string url, string userName, string password, string data) {
WebRequest request = WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
request.Credentials = new NetworkCredential(userName, password);
byte[] bytes = Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream()) {
requestStream.Write(bytes, 0, bytes.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
return reader.ReadToEnd();
}
}
}
}
return null;
}

Resources