I'm trying to send large json string in my c# application to an asp.net page using querystring (POST method), but because the string is too long it give me this msg: Invalid uri: the uri link is too long.
Is there is another solution for my problem !?
if(allRecords.Count > 0)
for (int j = 0; j < allRecords.Count; j++)
{
queryString += JsonConvert.SerializeObject(allRecords[j], Newtonsoft.Json.Formatting.Indented);
}
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(queryString);
// Set up Request.
HttpWebRequest webReq = WebRequest.Create(onlineApp) as HttpWebRequest;
webReq.ContentType = "text/plain";
webReq.Method = "POST";
webReq.Credentials = CredentialCache.DefaultCredentials;
webReq.ContentLength = data.Length;
// Send Request.
Stream newStream = webReq.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
// get Response.
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tt = reader.ReadToEnd();
reader.Close();
response.Close();
I think your problem in your WebRequest , when you create new Webrequest , check you webrequest string.
Related
I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data
I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}
I have an application written in c#.NET 2.0 Windows app. I am trying to implement web crawler using HttpWebRequest & HttpWebResponse. In this application i am using both http get & post request for a third part web sites. this web site provides user account for its members.
i am trying to login this sites using positing data then entering into my profile page & then trying to make another GETrequest & then make another POST request with post data.
but i am not able to make successfull request .
it through an error
"The server committed a protocol violation. Section=ResponseHeader
Detail=Header name is invalid"
then i set <httpWebRequest useUnsafeHeaderParsing="true" /> in app.config files. after that
it throw an error The underlying connection was closed:
The connection was closed unexpectedly : System.Net.WebException.
anybody can tell me what the reason for showing this error
my code below.
request.CookieContainer = objContainer;
request.KeepAlive = true;
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//=======================================================================
StringBuilder strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("j_username=username");
strLinkBuilder.Append("&j_password=password");
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "j_security_check");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = strLinkBuilder.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
strServerResponse = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
//request.CookieContainer = objContainer;
request.KeepAlive = true;
// request.Method = "POST";
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("finYr=2012");
strLinkBuilder.Append("&qrtr=3");
strLinkBuilder.Append("&frmType=24Q");
strLinkBuilder.Append("&download_conso=Go");
strLinkBuilder.Append("&requestnsdlconsoForm_SUBMIT=1");
Dictionary<string, string> objNameval = TraceHiddenField(strServerResponse, "");
foreach (KeyValuePair<string, string> pair in objNameval)
{
strLinkBuilder.Append("&" + pair.Key + "=" + pair.Value);
}
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
// Set the Method property of the request to POST.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
// request.ServicePoint.Expect100Continue = false;
request.UserAgent = "Mozilla/4.0 (compatible;)";
request.ProtocolVersion = HttpVersion.Version10;
// Create POST data and convert it to a byte array.
postData = strLinkBuilder.ToString();
byte[] byteData = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteData.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add( response.Cookies);
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteData, 0, byteData.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
I'm trying to get the userID of a Facebook user, I already have the access_token and I use http request to do it. My simple problem is that : I want the user's id but my program just crash... I use WPF, C# Here is my little call :
var url = string.Format("https://graph.facebook.com/me?access_token=" + token + "&response_type=id");
var req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "'access_token='" + token;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
var stream = req.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
WebResponse response = req.GetResponse();
aTextBox.Text = ((HttpWebResponse)response).StatusDescription;
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Thanks!
Don't use Web Browser for this! You may use HttpWebRequest for that kind of things:
string url = "https://graph.facebook.com/me?access_token=" + token + "&response_type=id";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseData = readStream.ReadToEnd();
I have this php code in server :
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
and i am sending post data by httpwebrequest in c# :
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://127.0.0.1/22") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
static html codes of php page are shown.
but nothing of posted value are shown in messagebox .that means no data are posted.
what is wrong?
You need to get the bytes of the data.
Try this code, from this guy's blog post.
public string Post(string url, string data) {
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim()+"\n";
}