I am trying to create a webservice. I am successfully able to send HttpClient Request to web service and getting response too.
What I want ?
I am sending some HttpHeaders with the POST request like userAgent, or any CustomHeader. That Header I want to read in webservice method. I don't know how to get Header list ?
I created webservice in C#.
public class Service1 :IService1{
public string putData(Stream data)
{
string response = string.Empty;
try
{
HttpContext ctx = HttpContext.Current;
string headerValue = ctx.Request.Headers["tej"];
StreamReader reader = new StreamReader(data);
string xmlString = reader.ReadToEnd();
StringReader sr = new StringReader(xmlString);
MySqlCommand cmd = new MySqlCommand();
DataSet ds = new DataSet();
ds.ReadXml(sr);
//my logic here....
return "Passed";
}
catch (Exception ex)
{
return "Failed";
}
}
}
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "putdata")]
string putData(Stream sDatabase);
}
Please try following using WebOperationContext.Current.IncomingRequest object.
public class Service1 :IService1
{
public string putData(Stream data)
{
try
{
//reading headers
IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
WebHeaderCollection headers = request.Headers;
foreach (string headerName in headers.AllKeys)
{
Console.WriteLine(headerName + ": " + headers[headerName]);
}
//---- rest of the code
}
catch (Exception ex)
{
return "Failed";
}
}
}
Related
I created the WcfService and it worked fine. Now I need to to change the return value from int to List. After modified I get the error "The remote server returned an error: (500) Internal Server Error" on my test webpage. Also the other methods that I didn't modify get the same error too. Would someone tell me how to make it works.
The page to send the request:
protected void getOrders_Click(object sender, EventArgs e)
{
string serviceUrl= url + "/checkOrders?OrderNum=test123";
string result = "";
HttpWebRequest request = WebRequest.Create(serviceUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
lbl.Text = result;
}
There is the code on my IServer.CS
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "checkOrders?OrderNum={OrderNum}")]
//int getAllOrders(string input);
List<OrderDetails> getAllOrders(string input);
[DataContract(Name = "OrderDetails")]
public class OrderDetails
{
[DataMember]
public List<OrderDetails> lstOrderDetails;
}
How to Send and receive excel data using web service
I have created a web application to send excel file data to a web service.
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:58959/RESTServiceImpl.svc/PostFile");
request.ContentType = "application/vnd.ms-excel";
request.Headers.Add("filename", "fooBar.xls");
request.Method = WebRequestMethods.Http.Post;
byte[] fileData = System.IO.File.ReadAllBytes("C:\\Users\\Public\\Documents\\Forecast Pro TRAC\\Input\\Book1.xls");
request.ContentLength = fileData.Length;
using (System.IO.BinaryWriter postStream = new System.IO.BinaryWriter(request.GetRequestStream()))
{
postStream.Write(fileData);
postStream.Flush();
postStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK);
string responseMessage = string.Empty;
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseMessage = sr.ReadToEnd();
}
System.Diagnostics.Debug.WriteLine(responseMessage);
}
Now I need to receive that excel data from WCF application. So I have done something like below code. I am getting total bytes that I am sending. What are exact things I need to do in both end to send and receive excel data.
[ServiceContract]
public interface IRESTServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "PostFile")]
string PostFile();
}
public class RESTServiceImpl : IRESTServiceImpl
{
public string PostFile()
{
var httpRequest = HttpContext.Current.Request;
var bites = httpRequest.TotalBytes;
return httpRequest.FilePath;
}
}
I am very new in web service and this is my first application. So please please help me.
Thanks in advance.
I have solved the solution and here is the working code
public class RestServiceImpl : IRestServiceImpl
{
public string PostFileRest(Stream fileContents)
{
var httpRequest = HttpContext.Current.Request;
var filePath = "C:\\file.xls"; //excel filePath for local
var bites = httpRequest.TotalBytes;
//Convert stream to byte array
byte[] reqBytes = readRequest(fileContents, bites);
byte[] decodedReqBytes = HttpUtility.UrlDecodeToBytes(reqBytes);
string json = System.Text.Encoding.UTF8.GetString(reqBytes);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
MemoryStream stream = new MemoryStream(reqBytes);
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
stream.WriteTo(file);
file.Close();
stream.Close();
return json ;
}
#region Convert Stream to byte array
private byte[] readRequest(Stream fileContents, int bites)
{
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
int BUFFER_SIZE = bites;
int iRead = 0;
int idx = 0;
Int64 iSize = 0;
memStream.SetLength(BUFFER_SIZE);
while (true)
{
byte[] reqBuffer = new byte[BUFFER_SIZE];
try
{
iRead = fileContents.Read(reqBuffer, 0, BUFFER_SIZE);
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
if (iRead == 0)
{
break;
}
iSize += iRead;
memStream.SetLength(iSize);
memStream.Write(reqBuffer, 0, iRead);
idx += iRead;
}
byte[] content = memStream.ToArray();
memStream.Close();
return content;
}
#endregion
}
The Interface-
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "PostFileRest")]
string PostFileRest(Stream fileContents);
}
I have a WCF project that returns a DataSet in XML format. This is in my service contract:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "RunSavedReportByID", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
DataSet RunSavedReportByID(int savedReportID);
I have another project that consumes this service, and I'm trying to get the DataSet back. I call my service like so:
strResults = objUtility.GetData("RunSavedReportByID", JsonConvert.SerializeObject(new { savedReportID = savedReportID }));
GetData looks like this:
public string GetData(string method, string data)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(externalServiceUrl + method);
ASCIIEncoding encoding = new ASCIIEncoding();
var postData = encoding.GetBytes(data);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(postData, 0, data.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
return reader.ReadToEnd().Trim();
}
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
return null;
}
The string that I get is weird. It looks like this when I save it to a text file:
"\"<DataSet><xs:schema id=\\\"NewDataSet\\\" xmlns:xs=\\\"http:\\/\\/www.w3.org\\/2001\\/XMLSchema\\\" xmlns:msdata=\\\"urn:schemas-microsoft-com:xml-msdata\\\"><xs:element name=\\\"NewDataSet\\\" msdata:IsDataSet=\\\"true\\\" msdata:UseCurrentLocale=\\\"true\\\"><xs:complexType><xs:choice minOccurs=\\\"0\\\" maxOccurs=\\\"unbounded\\\"><xs:element name=\\\"Table\\\"><xs:complexType><xs:sequence><xs:element name=\\\"InvoiceNo\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"GuestID\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"ConsumerID\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"ContactTitleName\\\" type=\\\"xs:string\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"LastName\\\" type=\\\"xs:string\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"FirstName\\\" type=\\\"xs:string\\\" ... blah blah blah ... \\/NewDataSet><\\/diffgr:diffgram><\\/DataSet>\""
Not surprisingly, after I create and XmlDocument and call LoadXml, I get
Data at the root level is invalid. Line 1, position 1.
If I strip out the first and last quotation marks and unescape the string like so
strResults = Regex.Unescape(strResults);
strResults = strResults.Remove(0, 1);
strResults = strResults.Remove(strResults.Length - 1, 1);
then the XML loads fine, so the XML itself is legit.
So after all this exposition, my questions are
1) Why does the string I get back look so weird? What's up with all the extra quotation marks and backslashes?
2) Is there a better way of getting rid of the bad stuff before loading the XML?
I am bit new in rest service
I have service as below
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate="AuthenticateJSON/?username=username&password=password")]
public Response.Authenicate Authenticate(string username,string password)
{
var returnObject = new Authenicate();
try
{
returnObject.Response = "True";
}
catch (Exception exceptionObject)
{
returnObject.IsError = true;
returnObject.ErrorMessage = exceptionObject.Message;
}
return returnObject;
}
And I consume Service by below code
string input = #"{'himanshu','password'}";
var newUser = new User();
newUser.username = "username";
newUser.password = "username";
var input = new JavaScriptSerializer().Serialize(newUser);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:20620/Services/User/OperationActiveDirectory.svc/AuthenticateJSON/?username=username&password=password");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";//POST/GET
string responseText = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(input);//any parameter
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
but i am facing below error while execution
Could some one suggest me what i am doing wrong here
I made a rest web service with the service contract as shown below
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "postdataa?id={id}"
)]
string PostData(string id);
Implementation of the method PostData
public string PostData(string id)
{
return "You posted " + id;
}
Code in Android to post data in web service
HttpClient httpclient = new DefaultHttpClient();
HttpHost target = new HttpHost("192.168.1.4",4567);
HttpPost httppost = new HttpPost("/RestService.svc/postdataa?");
String result=null;
HttpEntity entity = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "1"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(ent);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(target, httppost);
entity = response.getEntity();
//get xml result in string
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
The problem is that the xml result shows and the value of the parameter is missing:
<PostDataResponse xmlns="http://tempuri.org/"><PostDataResult>You posted </PostDataResult></PostDataResponse>
I do not know what went wrong.
Since you are using REST service, give this a try:
private static char[] GetData(String servicePath) throws Exception
{
InputStream stream = null;
String serviceURI = SERVICE_URI;//this is your URI to the service
char[] buffer = null;
try
{
if (servicePath != "")
serviceURI = serviceURI + servicePath;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(serviceURI);
request.setHeader("Accept", "application/xml");
request.setHeader("Content-type", "application/xml");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
// Read response data into buffer
buffer = new char[(int)responseEntity.getContentLength()];
stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
}
}
catch (Exception e)
{
Log.i("Survey Application", e.getMessage());
throw e;
}
return buffer;
}
Invoke this method using
try
{
char[] buffer = GetData("postdataa/" + id);
if (buffer != null)
//Build your XML object
}
catch (Exception e)
{
}