I want to do a create via a webservice which needs a uri like this:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
my problem is, element is all information of an email with html body, which is about 6000 characters.
I want to call the url like this:
var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
but it breaks at
var response = request.GetResponse();
and says the uri is too long.
I can't change the server's max length of the url and the webservice needs the parameters in the url.
I haven't found a suitable solution for me yet so any help is appreciated.Update:
For anyone facing the same issue, the solution that worked for me was to put my query into an byte-Array like
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
and writing that into the webrequest instead of my queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
You can put data in the body of the request with something a little like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<url>/webservice.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonContent = JsonConvert.SerializeObject(new YourObject
{
// Pseudo code... Replace <...> with your values etc
Operation = <YourOperation>,
ElementType = <YourElementType>,
Element = <YourElement>,
// etc...
});
HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync("youroperation/", httpContent);
}
// Do something with response if you want
}
This is JSON based but could be anything you want to pass... This is a simple example that will hopefully give you an idea of how you can proceed.
You need to split the urlToUse at the question mark:
Something like this (not tested)
string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
Good luck with your quest.
Related
Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.
I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);
With the following code, I'm trying to post a html form and expecting a complete html page-
string reqString = "destination=&calldate_from=2015-08-01&calldate_to=2015-08-02&call_status=ANSWERED&search=Search";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.100.70:83/report/outgoing/search");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestData.Length;
request.Host = "192.168.100.70:83";
request.Method = "POST";
Cookie idcookie = new Cookie("PHPSESSID", "19fv94lhgtdr80st6ig366q461") { Domain = "192.168.100.70" };
Cookie bdcookie = new Cookie("ciIPPBXOBd", "nMXEiUJiSU%3D") { Domain = "192.168.100.70" };
request.CookieContainer = request.CookieContainer ?? new CookieContainer();
request.CookieContainer.Add(idcookie);
request.CookieContainer.Add(bdcookie);
// Get the request stream.
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestData, 0, requestData.Length);
// requestStream.Flush();
requestStream.Close();
WebResponse response = request.GetResponse();
var res = ((HttpWebResponse)response).StatusDescription; //gets OK here.
StreamReader reader = new StreamReader(response.GetResponseStream());
string returnValue = reader.ReadToEnd(); //found empty
reader.Close();
Code is running without throwing any exception. But I can not retrieve the full html. How can I do that?
My API method which generates my xml looks like this (which is fine)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
but somewhere in between my api method
return Request.CreateResponse(HttpStatusCode.OK, res);
and where I grab the response from
string api_response = client.UploadString(myurl, myRequest)
my api_response string above looks like below
"\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>
which causes my XDocument.Parse to fail
Edit: more details
I am getting the response by this code
HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.ContentType = "text/xml; charset=utf-8";
httpRequest.Accept = "text/xml";
httpRequest.Credentials = new NetworkCredential(userName, password);
byte[] bytesToWrite = Encoding.UTF8.GetBytes(root.ToString());
using (Stream st = httpRequest.GetRequestStream())
{
st.Write(bytesToWrite, 0, bytesToWrite.Length);
}
HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
string read = reader.ReadToEnd();
return read;
The read returns well formed xml:
it is only after I CreateResponse when the extra backslashes come in play (looking at the string clicking the magnify glass option)
When I return the response back from my api (as text on internet explorer), my actual text is like so "
Figured it out
replacing my with ResponseMessage
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) {
RequestMessage = Request,
Content = new StringContent(content)
};
return ResponseMessage(httpResponseMessage);
Okay changed
return Request.CreateResponse(HttpStatusCode.OK, res);
to
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted) {
RequestMessage = Request,
Content = new StringContent(content)
};
return ResponseMessage(httpResponseMessage);
I basically have some idea how to use HttpWebRequests but I am pretty newbie. So I want to submit the following token with the Post method.
authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D
What it does is click a button and send the text "TEST TEST TEST", this is the token I am getting from firebug when I click the button I want to.
To send some data with a Http Post Request you can try using the following code:
check 'var serverResponse' for server response.
string targetUrl = "http://www.url.url";
var postBytes = Encoding.Default.GetBytes(#"authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D");
var httpRequest = (HttpWebRequest)WebRequest.Create(targetUrl);
httpRequest.ContentLength = postBytes.Length;
httpRequest.Method = "POST";
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(postBytes, 0, postBytes.Length);
var httpResponse = httpRequest.GetResponse();
using (var responseStream = httpResponse.GetResponseStream())
if (responseStream != null)
using (var responseStreamReader = new StreamReader(responseStream))
{
var serverResponse = responseStreamReader.ReadToEnd();
}
Yet another solution:
// you can get the correct encoding from your site's response headers
Encoding encoding = Encoding.UTF8;
string targetUrl = "http://example.com";
var request = (HttpWebRequest)WebRequest.Create(targetUrl);
var formData = new Dictionary<string, object>();
formData["authenticity_token"] = "pkhn7pwt3QATOpOAfBERZ+RIJ7oBEqGFpnF0Ir4RtJg=";
formData["question[question_text]"] = "TEST TEST TEST";
bool isFirstField = true;
StringBuilder query = new StringBuilder();
foreach (KeyValuePair<string, object> field in formData)
{
if (!isFirstField)
query.Append("&");
else
isFirstField= false;
query.AppendFormat("{0}={1}", field.Key, field.Value);
}
string urlEncodedQuery = Uri.EscapeDataString(query.ToString());
byte[] postData = encoding.GetBytes(urlEncodedQuery);
request.ContentLength = postData.Length;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (BinaryWriter bw = new BinaryWriter(request.GetRequestStream()))
bw.Write(postData);
var response = request.GetResponse() as HttpWebResponse;
// TODO: process response