problem in uploading data with HttpWebRequest - c#

Request you to please help me to solve my problem. I am new to web-services and HTTP.
I wrote following code to update data to website. Code run; but I am not able to see my data if uploaded. Here we have facility to see what data is getting uploaded but I am not able to see my data.
// Above URL is not real as I do not want to disclose real URL as of Now
Uri targetUrl = new Uri("http://www.x86map.com/post-embed/ewspost");
HttpWebRequest request = null;
StringBuilder sb = new StringBuilder();
Stream requestStream = null;
try
{
request = (HttpWebRequest)WebRequest.Create(targetUrl);
using (StreamReader inputReader = new StreamReader("C:\\SupportXml.xml"))
{
sb.Append(inputReader.ReadToEnd());
}
String postData = sb.ToString();
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
request.KeepAlive = true;
request.Accept = "*/*";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Language", "en-us");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8,q=0.66,*;q=0.66");
requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
finally
{
if (null != requestStream)
requestStream.Close();
}
URL I mentioned in Code is not real. Please let me know what is the problem in my code.
Following is the Java code working perfect. I want to convert same code in C#.
// Above URL is not real as I do not want to disclose real URL as of Now
String urlString = "http://www.x86map.com/post-embed/ewspost";
StringBuffer s = new StringBuffer();
try
{
String line = null;
BufferedReader input = new BufferedReader(new FileReader("C:\\SupportXml.xml"));
while ((line = input.readLine()) != null)
{
s.append(line);
s.append(System.getProperty("line.separator"));
}
String xmlDataString = s.toString();
int length = xmlDataString.length();
System.out.println("length " + length);
URL url = new URL(urlString);
System.out.println(url.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setUseCaches(false);
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (String.valueOf(length)));
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Accept-Language", "en-us");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8,q=0.66, *;q=0.66");
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
BufferedReader reader = new BufferedReader(new StringReader(xmlDataString));
System.out.println("Proxy Used :" + connection.usingProxy());
int dataRead;
bos.write("XML_string=".getBytes());
while ((dataRead = reader.read()) != -1)
{
bos.write(dataRead);
}
bos.flush();
bos.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String res = null;
while ((res = br.readLine()) != null)
{
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Please help me to resolve this issue.
Thanks and Regards,
map125

You may find it helps to include
requestStream.Flush();
before .Closeing it.
Stream.Flush

I do not see the code that actually gets the response. Is this want is missing?
using (var r = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
result = r.ReadToEnd();

Related

Rest Client Authorization error

I want to call a rest client with basic authorization. I tried this but got a Unauthorized(401) exception in c# :
HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://someurl.com");
client.Method = "POST";
client.UseDefaultCredentials = true;
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(mailinglist.ToString());
client.ContentLength = bytes.Length;
using (var writeStream = client.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
client.ContentType = "application/json";
NetworkCredential nc = new NetworkCredential("8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
//string credentials = String.Format("{0}:{1}", "8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
//byte[] bts = Encoding.ASCII.GetBytes(credentials);
//string base64 = Convert.ToBase64String(bts);
client.PreAuthenticate = true;
//string authorization = String.Concat("Basic ", base64);
//Utils.WriteLog("Addaudience", authorization);
//client.Headers.Add(HttpRequestHeader.Authorization, authorization);
client.Credentials = nc;
client.Accept = "application/json";
using (var response = (HttpWebResponse)client.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
Please help me and tell me what is my mistake? I also tried to put Authorization string in the headers but not working.
Thanks.

verifying iOS in app purchase receipt with C#

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

Bad Request trying to retrieve Tokens from Google with C#

I'm trying to replicate the process detailed here; https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse
in C#
String authorizationCode = String.Empty;
String consumerKey = String.Empty;
String consumerSecret = String.Empty;
String redirectUrl = String.Empty;
String grantType = String.Empty;
String requestContent = String.Empty;
HttpWebRequest request = null;
byte[] byteArray = null;
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
String serverResponse = String.Empty;
byte[] authorizationResult = null;
try
{
authorizationCode = HttpUtility.UrlEncode(context.Request.QueryString["code"]);
consumerKey = Properties.Settings.Default.GoogleConsumerKey;
consumerSecret = Properties.Settings.Default.GoogleConsumerSecret;
redirectUrl = Properties.Settings.Default.RedirectUrl;
grantType = "authorization_code";
request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Method = "POST";
requestContent = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_url={3}&grant_type={4}",authorizationCode,consumerKey,consumerSecret,redirectUrl,grantType);
byteArray = Encoding.UTF8.GetBytes(requestContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
serverResponse = HttpUtility.UrlDecode(reader.ReadToEnd());
reader.Close();
dataStream.Close();
response.Close();
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
}
The Trouble is when calling GetResponse() I am getting Bad Request.
The ConsumerKey & Secret is the one I got from Google when I registered my application. The authorizationCode comes from Google as well.
any ideas what I am doing wrong?
Thanks in advance.
I had the same issue :
The "using" keyword solved it for me. follow the link:
https://stackoverflow.com/a/1968543/1820776

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

file format issue when using HTTP POST via C# to upload a picture file

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.

Categories