How to send array HttpPost to Apache Server - c#

I can't sending my array with DoPostMethod. Php code is working but I can't convert it to C#.Php code is
$numbers = array('50XXXXXXXX', '50XXXXXXXX', '50XXXXXXXX', '50XXXXXXXX');
$message = 'TEST';
$title = 'MAS API';
$veriler = array(
'apiNo' =>'1',
'user' =>’user_name’,
'pass' =>'pasword',
'mesaj'=>$message,
'numaralar' =>$numbers,
'baslik' =>$title,
);
$ozel_mesaj = sms_gonder("http://------",$veriler);
My code is below
DoRequest(string requestUrl, string requestMethod, string requestData){
WebRequest request = WebRequest.Create(requestUrl);
request.Method = requestMethod;
string postData = requestData;
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);
this.ServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();}
but i can send with ajax method
$.ajax({
"url": "myUrl",
"type": "post",
data:{
"apiNo": "apiNo",
"user": "user_name",
"pass": "password",
"mesaj": "DENEME123",
"numaralar":"numbers",
"baslik":"baslik"
},
success: function (data) {
if (data != NULL)
alert(data)
else
alert("Kayıt Eklenemedi")
}
I think my requestData is wrong. My RequestData is below:
string xmlRequest = "[{{apiNo=\"apiNo\"}, {user=\"user_name\"},{pass=\"password\"},{mesaj=\"DENEME2\"},{numaralar=\"{0000000000}\"},{baslik=\"baslik\"}}]";
How can I do that? Thanks

Here's a super basic way to do it. In this example, I am manually writing out the post parameters with a quick function that returns a string however, you could use JavascriptSerializer to properly convert a C# array (as well as reading inbound json returned by your webservice) which was recommended in another post answer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace doPostExampleForStackOverflow
{
static class Program
{
[STAThread]
static void Main()
{
string postReturn = doPostCall();
MessageBox.Show(postReturn);
Application.Exit();
}
static string doPostCall()
{
string URI = "https://webserver.com/post.php";
string myParameters = "username=" + Environment.UserName; /* Get local username (Windows) */
string result;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
result = wc.UploadString(URI, myParameters);
}
if (result.Length <= 0) {
return "Nothing came back from the webserver.";
} else {
return result;
}
}
}
}

I solved my problem using this
string URL = "myURL";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["apiNo"] = "apiNo";
formData["user"] = "user";
formData["pass"] = "pass";
formData["baslik"] = "baslik";
formData["numaralar"] = "{numaralar}";
formData["mesaj"] =" mesaj";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
and you can look at this link

Related

HttpWebRequest.getResponse() returning NULL

I am attempting to create a console app that sends a WebRequest to a website so that I can get some information back from it in JSON format. Once I build up the request and try to get response I just want to simply print out the data, but when I call httpWebRequest.getResponse() it returns NULL.
I have tried multiple other methods of sending the data to the the url but those are all giving me like 404, or 400 errors, etc. This method at least isn't giving me any error, just a NULL.
Here is a snapshot of the documentation I am using for the API (albeit the docs aren't complete yet):
Here is the console app code that I have right now:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.remot3.it/apv/v27/user/login");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("developerkey", "***KEY***");
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
email = "***EMAIL***",
password = "***PASSWORD***"
});
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
}catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.ReadLine();
}
Expected output is some JSON data, but I am getting a NULL back from getResponse().
Try to serialize the credential in your form and for header send as parameter for this class.
Check below for my code. It is not 100 % fit to your requirement, but atleast it will help to get through your logic.
Here is what I get Json Response from this code. Its work Perfect. Please remember to add timeout option on your webrequest and at the end close the streamreader and stream after completing your task. please check this code.
public static string httpPost(string url, string json)
{
string content = "";
byte[] bs;
if (json != null && json != string.Empty)
{
bs = Encoding.UTF8.GetBytes(json);
}
else
{
bs = Encoding.UTF8.GetBytes(url);
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (json != string.Empty)
req.ContentType = "application/json";
else
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Timeout = 30000;
req.ReadWriteTimeout = 30000;
//req.UserAgent = "test.net";
req.Accept = "application/json";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
using (WebResponse wr = req.GetResponse())
{
Stream s = wr.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
content = reader.ReadToEnd();
wr.Close();
s.Close();
reader.Close();
}
return content;
}

How to send raw data via POST to a WebApi

I'm trying to make POST to an external webapi sending "raw" data. I could successfully do it using for example Postman, but when I tried to do it in my MVC App, I get the following error: Specified value does not have a ':' separator. Parameter name: header.
This is my code for calling the webapi:
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
string postData = pToken;
//I THINK THE ERROR IS IN THE NEXT LINE:
request.Headers.Add(postData);
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
Write the pToken variable to request stream
PSUEDO CODE
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
var bytes = System.Text.Encoding.UTF8.GetBytes(pToken);
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}

How to passing variables to PHP Script [POST] using C#

I am using this code :
public void sendPostData(string url, string data)
{
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.UTF8.GetBytes(data);
req.ContentLength = bytes.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
}
PHP for POST processing :
<?php
if(#$_POST['filename'])
{
$data = filter_var($_POST['filename'], FILTER_SANITIZE_STRING);
$f = fopen($data.".txt", "w");
fclose($f);
}
?>
I am calling by this :
sendPostData("http://127.0.0.1/csharptest/index.php", "filename=myvariablehere");
So, all it does is create a file name "myvariablehere" on server instead of storing value in myvariablehere which holds the data.
I Want "myvariablehere" value stored on server.
Please lil help here !
Thanks
Try this code
public static class Upload
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}
}
and then simply call this
var response = Upload.Post("URL", new NameValueCollection() {
{ "fileName", "test" },
});

How to add query string and json data to httpWebRequest type POST

Javacode here:
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
And C# code, I want to replace "?access_token=dshfhsfhrthytrghfgbfhnytfht" by code, because the url use type POST. I find out that I can use WebRequest but i don't know how I use WebRequest to add Json data, so I use HttpWebrequest, Http Webrequest can add query string by StringBuilder , but how i Write post data and json? In this code I just Write json data
public void sendTextMessage(string sender, string text) {
string json = "{ recipient: {id:"+sender+ "} , message: {text: \""+text+"\"}";
var request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/v2.6/me/messages?access_token=dshfhsfhrthytrghfgbfhnytfht");
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
/* Write like this
You must add you variable as postdata
*/
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

How to create Journal entry in QuickBooks Online

I am trying to use C# to create a Journal entry in Quickbooks Online V3 API.
Things I have done:
Check JSON Values and format
Checked Header and accept.
Header info:
Accept : application/json
Authorization : OAuth oauth_token="************",oauth_nonce="cfc36792-8f9a-4202-9fec-be0a610eed8e",oauth_consumer_key="************",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1435189421",oauth_version="1.0",oauth_signature="***"
Content-Length : 642
Content-Type : application/json
Host : qb.sbfinance.intuit.com
//till here everything is fine not sure about last two lines..
//not sure should i add this to my header or not..
X-NewRelic-ID : UQMAU15RGwcAUllSDwc=
X-NewRelic-Transaction : PxQAVVRUCgMIUiRXdHMBICETGlUDChAHHEAPVgoPBgILU3xUciMFJCEUG0MDUwFVAV1WVBVs
My code:
public static void Main()
{
// JournalEndPoint lnew = new JournalEndPoint();
// string Json=lnew.CreateJournal();
string consumerKey = "***";
string consec = "***";
string appkeysec1 = "***";
string appkey1 = "***";
string returnvalue = ExecuteV3Query(consumerKey, consec, appkey1, appkeysec1, "1397754725", "select * from employee where active=TRUE");
}
public static string ExecuteV3Query(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string CompanyId, string query)
{
string encodedQuery = RestSharp.Contrib.HttpUtility.UrlEncode(query);
string uri = string.Format("https://quickbooks.api.intuit.com/v3/company/{0}/journalentry", CompanyId, encodedQuery);
HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
httpWebRequest.Method = "POST";
string JSonvalue = CreateUserJson();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken, accessTokenSecret, httpWebRequest, null));
//HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
/*
* using (Stream data = httpWebResponse.GetResponseStream())
{
//return XML response
return new StreamReader(data).ReadToEnd();
}
*/
var result = "";
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
result = text;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
}
GetDevDefineHeader() will create header and return type is string.
In your url, I do not see the use of encoded query and why are you passing it?
Please check the docs for correct endpoints for CRUD and query operations-
https://developer.intuit.com/docs/api/accounting/JournalEntry
See this example for GET using dev defined-
https://gist.github.com/IntuitDeveloperRelations/0913b4c224de758fde0a
Similarly there is a post example here, you can write similarly for JE-
//string res = CreateV3Customer(consumerKey, consumerSecret, accessToken, accessTokenSecret, realmId);
public string CreateV3Customer(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string realmId)
{
StringBuilder request = new StringBuilder();
StringBuilder response = new StringBuilder();
var requestBody = "{\"FamilyName\":\"Jack\"}";
HttpWebRequest httpWebRequest = WebRequest.Create("https://quickbooks.api.intuit.com/v3/company/"+realmId+"/customer") as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken,accessTokenSecret,httpWebRequest, requestBody));
request.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(request.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
string customerr = new StreamReader(data).ReadToEnd();
return customerr;
}
}

Categories

Resources