passing parameters to json web service using HttpWebRequest - asp.net

I am having a problem in passing parameters to webservice which except POST data in JSON. I am using HttpWebRequest for this, following is the code i have tried so far, but everytime server returns any of these two errors:
Error 1:
{"command":null,"handle":null,"code":2003,"msg":"Required parameter missing","error":["Parameter 'login_handle' missing.","Parameter 'login_pass' missing."],"params":{"0":{"Key":"login_handle","Value":"test"},"1":{"Key":"login_pass","Value":"test"},"handle":"example.com"},"svTRID":null,"response":[]}
Error 2:
{"command":null,"handle":null,"code":2400,"msg":"Command failed","error":["Internal Server Error. resulted in the following error: array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":[],"svTRID":null,"response":[],"children":[{"command":"Internal Server Error.","handle":null,"code":2400,"msg":"Command failed","error":["array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":{"errno":2,"errstr":"array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object","errfile":"\/home\/ote\/httpapi\/v1\/index.php","errline":54},"svTRID":null,"response":[]}]}
Here is the code:
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
Dictionary<string, string> data = new Dictionary<string, string>();
data["login_handle"] = "test";
data["login_pass"] = "test";
System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
webReq.Method = "POST";
webReq.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
writer.Write(json);
writer.Close();
System.Net.WebResponse webResp = webReq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string s = sr.ReadToEnd().Trim();
}
catch (Exception ex)
{
string e = ex.Message;
}
If i use string data = "[login_handle:'username',login_pass:'password']"; instead of Dictionary<string, string> , i receive error number 2.

Never mind, i solved it myself, instead of using Dictionary type i used anonymous type like this var data = new { login_handle = "test", login_pass = "test" }; and it solved my problem.

What you should have done is create a DataContract class (we'll call JsonData) which has two DataMembers named login_handle and login_pass.
Then, in the DataContractJsonSerializer, pass typeof(JsonData) to the constructor.
This solution is the best because you cannot create complex types using an anonymous type. Also, by parenting your DataContracts you can easily create complex JSON.

Related

How to pass array to php url from c#? [duplicate]

Is it possible to pass parameters with an HTTP get request? If so, how should I then do it? I have found an HTTP post requst (link). In that example the string postData is sent to a webserver. I would like to do the same using get instead. Google found this example on HTTP get here. However no parameters are sent to the web server.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
GET request with multiple params:
curl --request GET --url
http://localhost:8080/todos/?limit=10&offset=2 --header
'content-type:application/json'
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value in URL

What is a BindAsync method with two params in the IBinding interface

In the Azure WebJobs SDK, we have the IBinding interface. This interface has a method BindAsync with two params, but I can't understand what is the first param object value and when this overload method will be called.
The same question related ITriggerBinding interface.
I have tried to find the answer in the SDK code source. I know that BindingSource contains a dictionary of parameters where the key is an argument name and value is an argument value that will be provided to the BindAsync method, but I cannot understand what these arguments are and where they come from?
UPDATE
IBinding.BindAsync Method Returns Task<IValueProvider>.
The usage of IBinding.BindAsync.
Microsoft.Azure.WebJobs.Host.Bindings.IBinding.BindAsync(Microsoft.Azure.WebJobs.Host.Bindings.BindingContext)
Sample Code
public async Task BindAsync_String()
{
ParameterInfo parameterInfo = GetType().GetMethod("TestStringFunction").GetParameters()[0];
HttpTriggerAttributeBindingProvider.HttpTriggerBinding binding = new HttpTriggerAttributeBindingProvider.HttpTriggerBinding(new HttpTriggerAttribute(), parameterInfo, false);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://functions/myfunc?code=abc123");
request.Content = new StringContent("This is a test");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/text");
FunctionBindingContext functionContext = new FunctionBindingContext(Guid.NewGuid(), CancellationToken.None, new TestTraceWriter(TraceLevel.Verbose));
ValueBindingContext context = new ValueBindingContext(functionContext, CancellationToken.None);
ITriggerData triggerData = await binding.BindAsync(request, context);
Assert.Equal(0, triggerData.BindingData.Count);
string result = (string)triggerData.ValueProvider.GetValue();
Assert.Equal("This is a test", result);
}
From sample code(HttpTrigger), you will find request, context. They are two params in BindAsync. You will know the usage of BindAsync.

Spring Resttemplate : how to post file and common String data at the same time

I meet a request to upload files with spring resttemplate to upload files
with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?
you can use the following code in your application to have both multipartfile and normal request parameters at the same time.
Replace the url with your own.
replace param and value according to your normal parameters.
String url ="http://example.com";
String fileAbsPath ="absolute path of your file";
String fileName = new File(fileAbsPath).getName();
Files.readAllBytes(Paths.get(fileAbsPath));
MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) {
#Override
public String getFilename() {
return fileName;
}
};
data.add("file", resource);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("file","application/pdf");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("param1", "value1")
.queryParam("param2", "value2")
HttpEntity<> entity =
new HttpEntity<> (data, requestHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result =restTemplate.exchange(
builder.toUriString(),
HttpMethod.POST,
entity,
String.class);
System.out.println(result.getBody());
you can use this code.
HttpHeaders headers = getCASHeaders(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("fileField", new FileSystemResource(""));//get file resource
params.add("stringfield", stringPayload);
HttpEntity requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<CasAssetApiResponse> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
This will send post call with two param, you can add more according to your wish.
Please have a look at this stackoverflow answer as well
I got the error "cannot be cast to java.lang.String" although my code does not have any casting.

Serializing using protobuf-net and sending as postdata in http

I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.

Embedded WebResource and FileStream

[assembly: System.Web.UI.WebResource("Project.ConfigurationFiles.Tools.xml", "text/xml")]
string resource = "Project.ConfigurationFiles.Tools.xml";
string pathXML =Page.ClientScript.GetWebResourceUrl(this.GetType(), resource);
XmlSerializer mySerializer = new XmlSerializer(typeof(ToolB));
using (FileStream myFileStream = new FileStream(pathXML, FileMode.Open))
{
The error I get:
Illegal characters in path.
I guess this happens because FilleStream need file and not url.
This exception occurs because GetWebResourceUrl function returns an HTTP address but FileStream expects a file path. From your code snippet I suppose you are trying to read the XML file that's embedded into the assembly and deserialize it back to an object. Here's how you could achieve this:
var executingAssembly = Assembly.GetExecutingAssembly();
var resource = "Project.ConfigurationFiles.Tools.xml";
using (var stream = executingAssembly.GetManifestResourceStream(resource))
{
var serializer = new XmlSerializer(typeof(ToolB));
var toolB = (ToolB)serializer.Deserialize(stream);
}

Resources