I am sending POST data to PHP webpage from my windows app using VB.net. The code is as follows:
Dim data As String = "this is a test data push"
Dim wc As New WebClient
wc.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
wc.UploadStringAsync(uri, data)
The data gets stored. In the PHP page, I am sending an XML response back to the phone
header('Content-type: text/xml');
echo '';
echo '<count>';
echo '<',$i,'>'
echo '</count>';
echo '';
How do I use WebClient to read the RESPONSE back? Any help would be appreciated. Thanks alot.
You need to subscribe to the UploadStringCompleted event. See http://msdn.microsoft.com/en-us/library/ms144239.aspx for more details, but here is an excerpt:
This method sends a string to a resource. The string is sent
asynchronously using thread resources that are automatically allocated
from the thread pool. Before uploading the string, this method
converts it to a Byte array using the encoding specified in the
Encoding property. To receive notification when the string upload
completes, you can add an event handler to the UploadStringCompleted
event.
Drilling farther in, you can see that even returns a UploadStringCompletedEventArgs object that includes the results via the Result property. See http://msdn.microsoft.com/en-us/library/system.net.uploadstringcompletedeventargs.aspx for more details.
Related
Hi i am new to API connect ... i have a use case where i have to merge responses coming from two endpoints in XML format based on certain conditions.
My flow in the assemble section is like this
1) INVOKE
(i make my
first service call
and capture the response
in a custom 'Response
object varibale' -XMLResponse1
2) INVOKE
(i make my
second service call
and here i am not using any
custom 'Response object varibale'
Instead i am using apim.getvaribale('message.body') to get the response
3)GATEWAYSCRIPT
Here i want to write my script for parsing the xml and merging the two responses
and send back the merged response to the consumer
I observed that the xml response is not getting captured in a custom Response object variable when i try to capture it like below
var test1= apim.getvariable('XMLResponse1');
test1.item(0).childNodes
it throws me an exception like this
test1.item is not a function
now for the second response like below where i am not capturing the response in a custom Response object variable it works well
var test2= apim.getvariable('message.body');
My question:
1)How do i capture the xml responses in a custom Response object variable?
2)How can i parse the response into a javascript object? are there any libraries supported in api connect?
Below is the samples found from IBM community. Hope this may help you.
**** Sample XML ****
<Routing>
<partner name="Partner A" key="1">
<from_ID>PartnerA-KEY1-INT</from_ID>
<to_ID>PartnerA-KEY1-EXT</to_ID>
<destination>PartnerA-KEY1-DESTINATION</destination>
</partner>
<partner name="Partner B" key="2">
<from_ID>PartnerB-KEY2-INT</from_ID>
<to_ID>PartnerB-KEY2-EXT</to_ID>
<destination>PartnerB-KEY2-DESTINATION</destination>
</partner>
<partner name="Partner C" key="3">
<from_ID>PartnerC-KEY3-INT</from_ID>
<to_ID>PartnerC-KEY3-EXT</to_ID>
<destination>PartnerC-KEY3-DESTINATION</destination>
</partner>
</Routing>
**** Corresponing Gateway Script *****
var response = apim.getvariable('XMLResponse1.body');
var objType = response.item(0);
var string = objType.getElementsByTagName("partner").item(0).getElementsByTagName("from_ID").item(0).textContent;
output ---> string = PartnerA-KEY1-INT
Why do you want to merge them in a GatewayScript node??
You could merge them in a mapping node, in wich you have 2 variables as input (refered to the output objects of your invokes) and one XML object as output...
If you have to apply some conditions or comparisons, you could do them in the code part of the mapping nodes
On Gmail Api documentation i read that i've to make an HTTP request at "/upload/gmail/v1/users/userId/messages/send" when sending message larger then 5mb but i don't find any example how to implement this using the Client Library in .net
All the examples on the site refer to the "messages.Send" function that takes as parameter a raw message and the user id but i saw that there's another overload that also take the stream of the content to upload and the content type of it.
The problem is that i've no clue how to correctly call it.
Does anyone have successfully achived it ?
Thx for your answer
Simone
Simone, it's means that you use simple upload:
uploadType=media. For quick transfer of smaller files, for example, 5 MB or less.
You must use Multipart upload or Resumable upload (https://developers.google.com/gmail/api/guides/uploads)
You can send a post query with payload (see CURLOPT_POSTFIELDS, if use a CURL) on the https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=your_access_token&uploadType=multipart. Payload must contain json encoded message. Structure of this message for example:
$message = [
'message' => [
'raw' => str_replace(['+', '/'], ['-', '_'], base64_encode($mimeString)),
'threadId' => $yourThreadId
]
];
Variable $mimeString must contain correct mime string
How would I send a raw POST request in Visual Basic .NET (2010)? When I say raw, I mean without using System.Net.WebRequest to form one, but rather by forming your own headers and sending them with the StreamWriter..
I think I know how to do it with a GET request, but I'm not sure how I would send a POST request.
...
Example GET request (NOTE THAT HERE I USE WEBREQUEST, WHICH I DON'T WANT TO):
Private Function HTTPGet(ByVal URL As String) As String
On Error GoTo fail
Dim Output As String = String.Empty
Dim Request As WebRequest = WebRequest.Create(URL)
Request.Method = "GET"
Using Response As WebResponse = Request.GetResponse
Using Stream As Stream = Response.GetResponseStream
Output = (New StreamReader(Stream)).ReadToEnd
End Using
End Using
Return Output
fail:
Return Nothing
End Function
If you really want to manually create these POST's, you will have to do a little research on HTTP requests and sockets. Sockets will create connections to a destination service and let you determine what data you want to send. To build the data properly, you will need to research what the format will need to be for an HTTP POST.
Check out this link to learn more about HTTP GET/POST. Scroll down to (The POST Method) to see a sample HTTP POST.
http://www.jmarshall.com/easy/http/
Here is a link on sockets:
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx
For reasons outlined here I need to review a set values from they querystring or formdata before each request (so I can perform some authentication). The keys are the same each time and should be present in each request, however they will be located in the querystring for GET requests, and in the formdata for POST and others
As this is for authentication purposes, this needs to run before the request; At the moment I am using a MessageHandler.
I can work out whether I should be reading the querystring or formdata based on the method, and when it's a GET I can read the querystring OK using Request.GetQueryNameValuePairs(); however the problem is reading the formdata when it's a POST.
I can get the formdata using Request.Content.ReadAsFormDataAsync(), however formdata can only be read once, and when I read it here it is no longer available for the request (i.e. my controller actions get null models)
What is the most appropriate way to consistently and non-intrusively read querystring and/or formdata from a request before it gets to the request logic?
Regarding your question of which place would be better, in this case i believe the AuthorizationFilters to be better than a message handler, but either way i see that the problem is related to reading the body multiple times.
After doing "Request.Content.ReadAsFormDataAsync()" in your message handler, Can you try doing the following?
Stream requestBufferedStream = Request.Content.ReadAsStreamAsync().Result;
requestBufferedStream.Position = 0; //resetting to 0 as ReadAsFormDataAsync might have read the entire stream and position would be at the end of the stream causing no bytes to be read during parameter binding and you are seeing null values.
note: The ability of a request's content to be read single time only or multiple times depends on the host's buffer policy. By default, the host's buffer policy is set as always Buffered. In this case, you will be able to reset the position back to 0. However, if you explicitly make the policy to be Streamed, then you cannot reset back to 0.
What about using ActionFilterAtrributes?
this code worked well for me
public HttpResponseMessage AddEditCheck(Check check)
{
var request= ((System.Web.HttpContextWrapper)Request.Properties.ToList<KeyValuePair<string, object>>().First().Value).Request;
var i = request.Form["txtCheckDate"];
return Request.CreateResponse(HttpStatusCode.Ok);
}
I have a message in a Journal of a Private queue (.\Private$\theQueue\Journal$)
The message was created by WCF and processed (thus on the Journal).
The problem is I want to get the message (the body is too large to view in the Admin Tools) so i have created the following code
MessageQueue myQueue = new MessageQueue(txtQueueName.Text);
Message peekByLookupId = myQueue.PeekById(txtLookUpId.Text);
StreamReader reader = new StreamReader(peekByLookupId.BodyStream);
txtResult.Text = reader.ReadToEnd();
but the StreamReader does not return any result for the ReadToEnd. however the Stream does have a length (peekByLookupId.BodyStream.Length) of 1676
does any one have the code to peek at the XML of the object which WCF created (using the DataContractFormatter)
Or does anyone know where is the DataContractFormatter, as i could use this deserialise the object. (I have added the System.Runtime.Serialization to the project and it still does not recognise the object)
Many thanks
In the end I pulled out the body stream as bytes (do not convert into a string). converted into hex and viewed in WinHex..
there has to be a better way