I have to accesss an get some data from one of API.This API has only mentoned this method.No documentation showing how to acess and all.Data will be returned as Json.
This is the product API
1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}
I have generated the Token and I tried to access it like this.But nothing is recieving.I found an example and tried to do like this.May be this is wrong.Can any one show me how to access and get the data.Please see my code below and thanks in advanced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
request.Method = "POST";
string postData = "Data to post here";
byte[] post = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
}
}
I think you should change these things:
content type
request.ContentType = "application/json";
the post data
string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";
the URI
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have error in
plz help to convert json to rcpts.
string json = JsonConvert.SerializeObject(rcpts);
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace sdd.Contact
{
public partial class Cantact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SabtButton_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://ippanel.com/services.jspd");
string[] rcpts = new string[] { "981111111" };
string json = JsonConvert.SerializeObject(rcpts);
request.Method = "POST";
string postData = "op=send&uname=aaaa&pass=0000&message=hello Test&to=" + json + "&from=+9810001010";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
System.Diagnostics.Debug.WriteLine(responseFromServer);
}
}
}
You can try Parse or DeserializeObject for this:
JObject json = JObject.Parse(rcpts);
Or
dynamic json = JsonConvert.DeserializeObject(rcpts);
Iam trying to integrate paypal ipn in my application,but Iam getting error like "An exception of type 'System.Net.WebException' occurred in System.dll" but was not handled in user code in streamwriter.I have tried the below code.Please suggest.
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
public partial class ipn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
}
string Identity_Token = "zkiMk_t - XXXXXagbIDrzPAChXuWIYVS66TXXXXXXXXXXXXXXXXXXXXXXXXXX";//From you paypal account
string txToken = Request.QueryString["tx"];
string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, Identity_Token);
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest += query;
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// If response was SUCCESS, parse response string and output details
if (strResponse.StartsWith("SUCCESS"))
{
Label1.Text = "OK";
}
else
{
Label1.Text = "NO";
}
}
}
Initially I'm login in to a secured webpage,then m getting the cookie manually and then i have to set the cookie while making another call to fetch data from authorized web url.
how can I make one cookie aware client which do not require to set the auth cookie again and again. it should automatically set the auth cookie and get the required data.
My code is
CPSession retVal = null;
if (guid != "")
retVal = TokenManager.getSessionInfo(guid);
ServicePointManager.ServerCertificateValidationCallback = delegate
{ return true; };
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(address);
httpWReq.CookieContainer = new CookieContainer();
Encoding encoding = new UTF8Encoding();
byte[] bdata = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "PUT";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.CookieContainer.SetCookies(new Uri(address), retVal.getAttributeValue(CookieType)); // here I'm setting cookie manually.
httpWReq.ContentLength = bdata.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(bdata, 0, bdata.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
You can create one cookie aware client like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace SunPowerService.Service
{
public class CookieAwareWebClient : WebClient
{
public CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}
}
and you can call it like this
using (var client = new CookieAwareWebClient())
{
Uri uri = new Uri("YourUrlToGetAuthCookie");
client.m_container.SetCookies(uri, strCookieVal);
jsonresponse = client.DownloadString(uri);
}
Apparently Google's encoding is UTF-8 as it's stated in it's html meta tag.
But when I open a search page for scharfes+s with ASP WebRequest.GetResponse(), it's full of unrecognized characters. Does someone know what's going on there?
For your convenience, code is pasted below
Asp Page
<form id="form1" runat="server">
<div>
<div runat="server" id="output"/>
</div>
</form>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
public partial class SearchEngineCaller : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest queryPage = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=scharfes+s");
queryPage.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)queryPage.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
output.InnerHtml = readStream.ReadToEnd();
}
}
What encoding should I use?
You have to set some HTTP headers for the HttpWebRequest object:
HttpWebRequest queryPage = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=scharfes+s");
queryPage.Credentials = CredentialCache.DefaultCredentials;
queryPage.Accept = "text/html";
queryPage.Headers["Accept-Charset"] = "utf-8";
queryPage.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0";
IMPORTANT: Setting the Accept-Charset is not enough, it's important to set the User-Agent, too (I copied the above user agent string from here). I tried this solution, and it works for me (test code).
Disclaimer: I'm pretty new to ASP.NET, so I'm figuring it out as I go along.
I'm trying to output the results of a function in my code behind page on the webpage itself.
Example:
Code Behind:
public string POSTResult(string e) { ... return TheResult; }
ASPX Page:
Output is: <%=POSTResult("argument")%>
However, loading the page errors, saying "The name 'POSTResult' does not exist in the current context."
I'm apparently doing something a bit off with how I'm getting to the code behind page from the ASPX page. My ASPX page has this at the top:
<%# Page Title="" Language="C#" MasterPageFile="~/master/default.Master" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Bitfork.login" %>
The listed CodeBehind value is the name of the code behind page.
ETA:
Contents of my code behind (login.aspx.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Bitfork.master
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string POSTResult(string e)
{
// variables to store parameter values
string url = "https://accounts.google.com/o/oauth2/token";
// creates the post data for the POST request
string postData = (e);
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// POST the data
using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter2.Write(postData);
}
// This actually does the request and gets the response back
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// dumps the HTML from the response into a string variable
responseData = responseReader.ReadToEnd();
}
return responseData;
}
}
}
Example of argument being passed, with API secret keys redacted:
code=[redacted]&client_id=[redacted]&client_secret=[redacted]&redirect_uri=http://localhost:60284/login.aspx&grant_type=authorization_code
ETA2:
I don't know if it's related, but it seems like my code behind page and my webpage are not communicating with each other at all. For instance, I can't access DIVs by ID in my code behind page to change their contents.