hey i am making an activation architecture in .net. I have written a script that posts the PHP variables, however, the PHP echos back a server response and i want to get that response back.
I have tried some code pieces but they don't work.
the sample php script is:
<?php
$name = $_POST['username'];
echo $name;
?>
i can't get the response, i.e. echo $name, i cant get it please help
my code is:
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(postBuffer, 0, postBuffer.Length)
Dim stream As Stream = request.GetResponse().GetResponseStream()
Dim reader As New StreamReader(stream)
Dim response As String
Dim newStream As Stream = request.GetRequestStream()
While response = reader.ReadLine()
response += reader.ReadLine()
End While
Return response
requestStream.Close()
thanks
You may want to check my Answer to this post.
It's a bit more complicated than the answer you need, but it will solve your problem.
The Second Example is what you want. But don't just copy it, you need the class and the reference too.
Hope it helps.
Related
I have a web server where there are a few php scripts. These scripts are web service whereby some data is passed and they return values in json format.
For e.g. : http://www.example.com/test.php?name=abcd&id=100
So far passing values in url is the method and its ok if there is short content. However if I have to pass 1 page worth of content/text to it then there must be another way.
Currently my code is:
Dim web_client As Net.WebClient = New Net.WebClient
Dim Info As String
Dim response As IO.Stream = web_client.OpenRead("http://example.com/auth.php?userid=102&password=123")
Dim stream_reader As New IO.StreamReader(response)
Info = stream_reader.ReadToEnd()
' Close the stream reader and its underlying stream.
stream_reader.Close()
response.Close()
print (Info) ' info has output which is in json format
Is the above method ok and secure ? However if I wish to pass large amounts of data or the method is not secure then what should I do ?
Thank you.
One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/
I have an internal server that is generating JSON every few minutes. I need to pass this to and external server so I can manipulate the data and then present it in web interface.
Here is my python that send the data to PHP script:
x = json.dumps(data)
print '\nHTTP Response'
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")
conn.request("POST", "/recieve/recieve.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()
and Here is my PHP to receive the data
$data = file_get_contents('php://input');
$objJson = json_decode($data);
print_r ($objJson);
My python script return with response status 200 which is good and it returns my JSON. But on the PHP side I want to be able to store this information to manipulate and then have a web client grab at it. However it appears that even if I say
print_r ($objJson);
when I visit the .php page it does not print out my object. I suppose the data is gone because file::input will read only and then end?
Don't use file_get_contents()
Just:
if($_POST){ echo "WE got the data"; }
and print_r will help you with where to go from there, if you are unfamiliar with PHP arrays.
Try to use named parameter containing your JSON data while sending data to PHP and try to use the $_POST superglobal array in PHP (because you obviously connecting via cgi or similar interface not via cli).
You can see all the POST data by printing your $_POST array:
print_r($_POST);
Here is what I did in the end as a quick fix
the python
x = json.dumps(data)
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection("myurl.com")
conn.request("POST", "/script.php", x, headers)
response = conn.getresponse()
text = response.read()
print "Response status: ",response.status,"\n",text
conn.close()
then I realized that the PHP was receiving the post data but I was having a hard time manipulating it. So I just sent the JSON to a receiving PHP file that wrote the data as file and then has another JavaScript request grab that.
the php
if($_POST){ echo "WE got the data\n"; } //thanks rm-vanda
$data = file_get_contents('php://input');
$file = 'new.json';
$handle = fopen($file, 'a');
fwrite($handle, $data);
fclose($handle);
exit;
Then from my client just a ajax request for the file and parsed it on the client side.
Eventually I have to rethink this but it works for now. I also have to rewrite over the new.json file each time new data comes in or parse the old data out on the JavaScript success callback. Depends what you want to do.
I have the following web method in my web api controller
public HttpResponseMessage PostMakeBooking(FacilityBookingRequest bookingRequest)
{
var returnStatus = HttpStatusCode.OK;
var json = new JavaScriptSerializer().Serialize(bookingRequest);
var response = Request.CreateResponse<CardholderResponse>(returnStatus, cardholderResponse);
return response;
}
When I make this call from my .NET app, my json string appears correctly when I seralize it
{"correlationId":null,"RequestId":"7ec5092a-342a-4e32-9311-10e7df3e3683","BookingId":"BK-123102","CardholderId":"123456","BookingFrom":"\/Date(1370512706448)\/","BookingUntil":"\/Date(1370523506449)\/","DeviceId":"ACU-01-R2","Action":"Add","LoginId":"tester","Password":"tester"}
However, when I made to call from my php script
public function web_request(){
$guid =self::getGUID();
$replace = array("{","}");
$guid = str_replace($replace, "", $guid);
$client = new Zend_Rest_Client("http://203.92.72.221");
$request= new myZendCommon_FacilityBookingRequest();
$request->RequestId =$guid;
$request->BookingFrom ="27/03/2013 05:30";
$request->BookingUntil ="27/03/2013 06:30";
$request->CardholderId ="E0185963";
$request->DeviceId ="ACU-B2-01-R1";
$request->BookingId ="111";
$request->Action ="Add";
$request->LoginId ="tester";
$request->correlationId ="(null)";
$request->Password ="tester";
$request = json_encode($request);
$response = $client->restPost("/ibsswebapi/api/facilitybooking",$request);
print_r($response);
exit();
The call goes to my web method, but when I serialize it using JavaScriptSerializer().Serialize(bookingRequest)
{"correlationId":null,"RequestId":null,"BookingId":null,"CardholderId":null,"BookingFrom":"\/Date(-62135596800000)\/","BookingUntil":"\/Date(-62135596800000)\/","DeviceId":null,"Action":null,"LoginId":null,"Password":null}
All the values are null.
Is something wrong with the script?
I believe Kiran is right. Not sure why some one has felt his answer is not useful. Anyways, my understanding is that you are creating a JSON string and doing a form post of the same. I guess in this case the content type is sent as application/www-form-urlencoded but request body is a JSON string. You can use Fiddler to see how the request is being sent by the PHP script. I don't have the PHP knowledge to tell you how you can post JSON but my guess is that if you just remove the JSON encoding line $request = json_encode($request);, it should be okay.
From ASP.NET Web API point of view, if the request has Content-Type: application/json header and the body has the right JSON or if the request has Content-Type:application/www-form-urlencoded header and the body has the form url encoded content like RequestId=7ec5092a-342a-4e32-9311-10e7df3e3683&BookingId=BK-123102 and so on, web API will absolutely have no problem in binding. Currently, the request is not being sent in the right format for web API to bind.
Are you sending the header Content-Type:application/json in your request?
Also add the following piece of code to catch any model state validation errors:
.
if (!ModelState.IsValid)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}
I have managed to send an xml via post using xmlhttprequest. I have also managed to read the whole xml syntax by an aspx page using
Dim reader As System.IO.StreamReader = New System.IO.StreamReader(Page.Request.InputStream)
Dim xmlData As String = ""
xmlData = reader.ReadToEnd()
I am now trying to read the xml from a php page. (I want to read the whole xml, headers and data)
using $_POST I am getting nothing
using file_get_contents("php://input") im getting the xml's data, no headers.
what am I doing wrong? How can I read the whole posted xml?
file_get_contents does the job i want.
althought mozilla displays the pure xml data file_get_contents has