I currently have an employee that is performing manual data entry by taking information from an application which was developed in-house and entering it into a vendor based applications form for class signups. This was not a real issue until official launch of the application, which now we already have 1300+ users with data requiring entry. What I want to achieve is an application which takes the user information we have already collected and automatically submits these forms on the vendor website. A web-service or direct access to the vendors database is out of the question (pricing is astronomical), so I really need this form automation to work. Here is the code I currently have, but don't seem to be getting anywhere with it. Any input would really help.
public static string HttpPost(string uri, string parameters)
{
WebRequest req = WebRequest.Create(uri);
string postData = parameters;
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return null;
//// parameters: name1=value1&name2=value2
//WebRequest webRequest = WebRequest.Create(uri);
////string ProxyString =
//// System.Configuration.ConfigurationManager.AppSettings
//// [GetConfigKey("proxy")];
////webRequest.Proxy = new WebProxy (ProxyString, true);
////Commenting out above required change to App.Config
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Method = "POST";
//byte[] bytes = Encoding.ASCII.GetBytes(parameters);
//Stream os = null;
//try
//{ // send the Post
// webRequest.ContentLength = bytes.Length; //Count bytes to send
// os = webRequest.GetRequestStream();
// os.Write(bytes, 0, bytes.Length); //Send it
//}
//catch (WebException ex)
//{
// Console.WriteLine("HttpPost: Request error");
// Console.Read();
//}
//finally
//{
// if (os != null)
// {
// os.Close();
// }
//}
//try
//{ // get the response
// WebResponse webResponse = webRequest.GetResponse();
// if (webResponse == null)
// { return null; }
// StreamReader sr = new StreamReader(webResponse.GetResponseStream());
// return sr.ReadToEnd().Trim();
//}
//catch (WebException ex)
//{
// Console.WriteLine("HttpPost: Response error");
// Console.Read();
//}
//return null;
} // end HttpPost
Related
I am trying to passing C# Web service Parameters to PHP Application but not getting below is my code. Actually I am passing username and password xml format because no buddy should not see that credential while passing.
Below is my C# Web service using asp.net web form button click to redirect PHP application.
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
StringBuilder strRequest = new StringBuilder();
string url = "http://xyz.in/getuser.php/";
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(username,password);
writer.Close();
rsp = req.GetResponse();
var sr = new StreamReader(rsp.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
}
Below is my button click code.
protected void Button2_Click(object sender, EventArgs e)
{
localhost.WebService objserv1 = new localhost.WebService();
Label.Text = objserv1.POSTXml("nagapavani", "tech#1234");
}
Actually when user will button click passing some values to web service and through web service want to pass that value to php application. Is there Other way to achieve that requirement. When I am going to button click not going to redirect and taken this code from google.
You could send the data as following. Convert it to a byte array and write it to the request stream:
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string data = "user=" + username + "&password=" + password;
string url = "http://xyz.in/getuser.php/";
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using (Stream PostData = WebReq.GetRequestStream())
{
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
using (StreamReader strReader = new StreamReader(stream))
{
return strReader.ReadToEnd();
}
}
WebResp.Close();
}
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
return String.Empty;
}
I am working on consuming a REST API and I am using basic authentication where password is encoded to Base64 as follows
private XmlDocument sendXMLRequest(string requestXml)
{
string destinationUrl = "https://serviceapi.testgroup.com/testtp/query";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("API_TEST_NR:Testnol1$"));
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.Method = "POST";
request.ContentLength = bytes.Length;
//request.Connection = "keep-alive";
request.ContentType = "text/xml";
request.KeepAlive = true;
request.Timeout = 2000;
request.MediaType = "text/xml";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
Stream responseStream;
using (response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
responseStream = response.GetResponseStream();
XmlReader reader = new XmlTextReader(responseStream);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
try { reader.Close(); }
catch { }
try { responseStream.Close(); }
catch { }
try { response.Close(); }
catch { }
return xmlDoc;
}
}
try { response.Close(); }
catch { }
return null;
}
I'm kind of new to working on Web Api's and I know that the API responds with an access x-token after successful authorization based on the API documentaion and I am not sure how to access or capture it from the HTTP headers.
May I know a good way I can achieve this?
This is easier than I thought just capturing with its name.
string xtoken= response.Headers["custom-header"];
Console.WriteLine(xtoken);
Try this as below, represents, Request Data Using the WebRequest Class.In most cases, the WebRequest class is sufficient to receive data. However, if you need to set protocol-specific properties, you must cast the WebRequest to the protocol-specific type. For example, to access the HTTP-specific properties of HttpWebRequest, cast the WebRequest to an HttpWebRequest reference.
private XmlDocument GetRootLevelServiceDocument(
string serviceEndPoint, string oAuthToken)
{
XmlDocument xmlDoc = new XmlDocument();
HttpWebRequest request = CreateHttpRequest(serviceEndPoint,
oAuthToken);
using (HttpWebResponse response =
(HttpWebResponse)request.GetResponse())
{
using (XmlReader reader =
XmlReader.Create(response.GetResponseStream(),
new XmlReaderSettings() { CloseInput = true }))
{
xmlDoc.Load(reader);
string data = ReadResponse(response);
if (response.StatusCode != HttpStatusCode.OK)
{
LogMsg(string.Format("Error: {0}", data));
LogMsg(string.Format(
"Unexpected status code returned: {0}",
response.StatusCode));
}
}
}
return xmlDoc;
}
I am verifying my ios in app purchase receipt on my server using C# web service
I got receipt as string by doing below in Xcode:
- (void) completeTransaction: (SKPaymentTransaction *)transaction
{
NSString* receiptString = [[NSString alloc] initWithString:transaction.payment.productIdentifier];
NSLog(#"%#",receiptString);
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
NSString *jsonObjectString = [receipt base64EncodedStringWithOptions:0];
}
and I am sending that string(receipt) to my C# web service as parameter.
Here is my web service method:
[WebMethod(Description = "Purchase Item Verify")]
public string PurchaseItem(string receiptData)
{
string returnmessage = "";
try
{
var json = "{ 'receipt-data': '" + receiptData + "'}";
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = Encoding.UTF8.GetBytes(json);
HttpWebRequest request;
request = WebRequest.Create("https://sandbox.itunes.apple.com/verifyReceipt") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = postBytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
var sendresponse = (HttpWebResponse)request.GetResponse();
string sendresponsetext = "";
using (var streamReader = new StreamReader(sendresponse.GetResponseStream()))
{
sendresponsetext = streamReader.ReadToEnd();
}
returnmessage = sendresponsetext;
}
catch (Exception ex)
{
ex.Message.ToString();
}
return returnmessage;
}
It always return {"status":21002}.
I have been searching for two days , but still can't find out the solution. Can someone help me, what am i wrong ?
**I am testing on sandbox that is why i use sandbox URL. I can verify the transaction receipt within my app.
I got solution
The final code that works for me is:
public string PurchaseItem(string receiptData)
{
string returnmessage = "";
try
{
// var json = "{ 'receipt-data': '" + receiptData + "'}";
var json = new JObject(new JProperty("receipt-data", receiptData)).ToString();
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = Encoding.UTF8.GetBytes(json);
// HttpWebRequest request;
var request = System.Net.HttpWebRequest.Create("https://sandbox.itunes.apple.com/verifyReceipt");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = postBytes.Length;
//Stream postStream = request.GetRequestStream();
//postStream.Write(postBytes, 0, postBytes.Length);
//postStream.Close();
using (var stream = request.GetRequestStream())
{
stream.Write(postBytes, 0, postBytes.Length);
stream.Flush();
}
// var sendresponse = (HttpWebResponse)request.GetResponse();
var sendresponse = request.GetResponse();
string sendresponsetext = "";
using (var streamReader = new StreamReader(sendresponse.GetResponseStream()))
{
sendresponsetext = streamReader.ReadToEnd().Trim();
}
returnmessage = sendresponsetext;
}
catch (Exception ex)
{
ex.Message.ToString();
}
return returnmessage;
Spending two and half days just to change a method. Thanks GOD.
Here's an alternative asynchronous implementation using HTTPClient:
public static async Task<string> CheckReceiptWithAppStore()
{
string responseStr = null;
string uri = "https://sandbox.itunes.apple.com/verifyReceipt";
string receiptData = // Get your receipt from wherever you store it
var json = new JObject(new JProperty("receipt-data", receiptData),
new JProperty("password", "paste-your-shared-secret-here")).ToString();
using (var httpClient = new HttpClient())
{
if (receiptData != null)
{
HttpContent content = new StringContent(json);
try
{
Task<HttpResponseMessage> getResponse = httpClient.PostAsync(uri, content);
HttpResponseMessage response = await getResponse;
responseStr = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
Console.WriteLine("Error verifying receipt: " + e.Message);
}
}
}
return responseStr;
}
The shared secret is not required for non-subscription based purchases.
For managing subscriptions, #Jerry Naing's answer also requires the provision of your shared secret (can be retrieved/generated from iTunes Connect). Easiest way to include this is just to add an additional property in the line defining the json var.
var json = new JObject(new JProperty("receipt-data", receiptData), new JProperty("password", "put_your_shared_secret_here")).ToString();
Failing to provide the shared secret will result in a 21004 status response.
This code example was also helpful to me and may help others: For C# developers there is a useful open-source project called APNS-Sharp which includes receipt verification code that works in ASP.NET. In particular, the Receipt.cs and ReceiptVerification.cs files in the Jdsoft.Apple.AppStore directory
Found it from this page about Xamarin: inapp purcasing ios Transactions and Verification
SDO REST API - The issue is that when I upload the file, it has no format and it looks like this: 98A9799C-CFB1-423B-A4AD-40609282F861 (2.7 MB) DELETE <--- this file needs to be picture.jpg
The file is simply picture.jpg
public string POST(string URI, string file)
{
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = AppVars.Username;
credentials.Password = AppVars.Password;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.Credentials = credentials;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
//I have also tried request.ContentType = "image/jpeg"; and ran into the same issue.
byte[] bytes = File.ReadAllBytes(file);
Stream os = null;
try
{
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{
WebResponse requestResponse = request.GetResponse();
if (requestResponse == null)
{ return null; }
StreamReader sr = new StreamReader(requestResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
Problem solved. It was a cache issue. I cleared my browser cache and I was able to view the image online.
I am working on a desktop application developed in C# (.NET environment).
This application connects to remote server using HttpWebRequest. If due to any reason my PC is disconnected from the internet and I re-connect it my application always gives request timeout for HttpWebRequest until I restart my whole application and if I again add new thread to my application after network d/c it works fine.
Is there any way to reset my network or anyone can tell me how does it work?
//my code is..
public String request(String add, String post, int time, String reff, int id, int rwtime)
{
try
{
if (rwtime == 0)
{
rwtime = 100000;
}
string result = "";
string location = "";
// Create the web request
HttpWebRequest req = WebRequest.Create(add) as HttpWebRequest;
req.ReadWriteTimeout = rwtime;
req.KeepAlive = true;
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.ContentType = "application/x-www-form-urlencoded";
req.Timeout = time;
req.Referer = reff;
req.AllowAutoRedirect = false;
req.CookieContainer = statictk.cc[id];
req.PreAuthenticate = true;
if (post != "")
{
req.Method = "POST";
string postData = post;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
// Set the content type of the data being posted.
req.ContentType = "application/x-www-form-urlencoded";
// Set the content length of the string being posted.
req.ContentLength = byte1.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
}
else
{
req.Method = "GET";
}
// Get response
try
{
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
// Get the response stream
location = response.GetResponseHeader("Location");
if (location == "")
{
Stream responseStream = response.GetResponseStream();
if (response.ContentEncoding.ToLower().Contains("gzip"))
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
else if (response.ContentEncoding.ToLower().Contains("deflate"))
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
StreamReader reader = new StreamReader(responseStream, Encoding.Default);
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
else
{
result = location;
}
response.Close();
if (result == "") result = "retry";
return result;
}
catch (Exception e)
{
log.store("errorinresponce", e.Message);
if (statictd.status[id] != "removed")
{
return "retry";
}
else
{
return "error";
}
}
}
catch(Exception f)
{
log.store("Networkerrorretry", f.Message);
if (f.Message == "The operation has timed out")
{
return "retry";
}
string ans = MessageBox.Show("There was a Network Error..Wish to Retry ?\nError msg : "+ f.Message, "Title", MessageBoxButtons.YesNo).ToString();
if (ans == "Yes")
return "retry";
else
{
Invoketk.settxt(id, "Not Ready");
return "error";
}
}
}
It sounds like your application is missing some error handling. A disconnect can happen at any time and your application should be able to handle it. Try to surround the network loop with a try-catch statement, and then catch for the different kinds of exceptions. Depending on what exception was thrown, you can then decide if you reconnect to the server silently or if you want to generate an error message.