I am making a Windows Phone 8 application where I need to send login credentials to web server(I am using RESTSHARP) and post authentication (response) , I have to do variety of tasks.
I was using the following code base but I am getting Not Acceptable error message.
var client = new RestClient("http://com.example");
var request = new RestRequest("/REsource/", Method.POST);
// Json to post
request.AddParameter("username", userName.Text);
request.AddParameter("password", Password.Text);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
client.ExecuteAsync(request, response =>
{
MessageBox.Show(response.StatusCode.ToString());
if (response != null && ((response.StatusCode == HttpStatusCode.OK) &&
(response.ResponseStatus == ResponseStatus.Completed))) // It's probably not necessary to test both
{
}
else if (response != null)
{
MessageBox.Show(string.Format
("Status code is {0} ({1}); response status is {2}",
response.StatusCode, response.StatusDescription, response.ResponseStatus));
}
});
I tried HTTPResponseMessage part of HTTPCLient also and but dont know how to send a POST .
Related
I've create Board List function by fetching json url via flutter
First I've crated into window exe it works properly like this below
But when I want to production via chrome or android
It is not working as this below
This is my code to fetch json url what did I do wrong?
Future<List<Schedule>> fetchBoardList() async {
final response = await http.get('http://192.168.10.109:8888/mcschedule/machine/');
String logResponse = response.statusCode.toString();
if (response.statusCode == 200){
//print('ResponseStatusCode: $logResponse'); // Check Status Code = 200
//print('ResponseBody: ' + response.body); // Read Data in Array
List<dynamic> responseJson = json.decode(response.body);
return responseJson.map((e) => new Schedule.fromJson(e)).toList();
} else {
throw Exception('error :(');
}
}
I have a .net application which sends the following request to a node js server:
System.Net.Http.HttpClient client = new HttpClient();
client.PostAsync("http://some_url.com", some_string);
What I want to do is extract some_string from the post request on my server.
The post request comes in but I am unsure how to get the string from it. What I do:
if (req.method == 'POST') {
var body = '';
req.on('data,', function (data) {
body += data;
console.log(data);
});
But this does not do anything. I can see the length of my data in the req.headers property but where is the data itself? Am I doing this correctly?
i want to know how i can get a json response from my node.js server and display the response on my web page
below is the request and reponse in json code
var request = require("request"),
username = req.body.username,
password = req.body.password,
url = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+username+"&pass="+password;
console.log("url is "+url);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
var msg = json_body.profile.user;//this is the message i want to show on my web page(msg)
console.log(msg); // get json response
}
}
);
You will first have to register express to use ejs:
app.engine('.html', require('ejs').__express);
then you can use res.render and pass your data to the view
res.render('index.html', {msg: json_body.profile.user});
After that you can access that via the EJS
<%= msg %>
If you need a working example, a good one can be found at:
https://github.com/strongloop/express/tree/master/examples/ejs
In my asp.net mvc 4 web app my action in the controller seems to return a invalid data to the jquery ajax callback... The action is doing a ping to an IP and it is called several times from several ajax calls in order to do pings to several IPs.
A piece of my action in the controller (below what is returned):
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = (int)(packetsLost < 4 ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return new JsonResult()
{
ContentType = "application/json;charset=utf-8",
Data = new
{
sent = 4,
received = 4 - packetsLost,
lost = packetsLost,
percentLost = (int) (packetsLost / 4 * 100),
responseStatus01 = statuses[0],
responseStatus02 = statuses[1],
responseStatus03 = statuses[2],
responseStatus04 = statuses[3],
responseMessage01 = responseStatuses[0],
responseMessage02 = responseStatuses[1],
responseMessage03 = responseStatuses[2],
responseMessage04 = responseStatuses[3],
rtt01 = rtt[0],
rtt02 = rtt[1],
rtt03 = rtt[2],
rtt04 = rtt[3],
ttl01 = ttl[0],
ttl02 = ttl[1],
ttl03 = ttl[2],
ttl04 = ttl[3],
minRtt = roundTripTimes.Count == 0 ? "0" : string.Format("{0}ms", roundTripTimes.Min()),
maxRtt = roundTripTimes.Count == 0 ? "0" : string.Format("{0}ms", roundTripTimes.Max()),
avgRtt = roundTripTimes.Count == 0 ? "0" : string.Format("{0}ms", roundTripTimes.Average())
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
and jquery ajax call:
ajax({
url: '/Controller/Action/',
type: 'POST'
}).then(function (data) {
var _data;
try {
_data = $.parseJSON(data);
}
catch (err) {
alert("Something went bad!!!");
}
}, function (data) {
var _data;
try {
_var = $.parseJSON(data.responseText);
}
catch (err) {
alert("Something went bad!!!");
}
});
1) When action returns http status code OK (200) data.responseText in the jquery ajax callback is empty so I convert data instead (that contains correct data) but for some reason it is crashing when converting using parseJSON(data): error catched says invalid character... I do not know why...
2) When action return http status code NotFound (404) data.responseText sometimes (not always) is empty and statusText within data is "error" so neither I do not understand it....
Action in the controller always is returning the correct data....
Could someone help me to detect this error? or right me in the right direction....
UPDATED:
From ie dev tools, in network, I have observed that some pings are cancelled and then when trying to process them it returns empty responseText to the ajax callback so when trying to parse it, it crashes. I have observed that If I set the timeout for ping to a lower value, for example, 750ms, it is working but if i use the default timeout for ping, that is, 5sec, then it does not work: some pings are cancelled and when trying to serve them they are returning empty responseText that cause it to crash when trying to parse in ajax callback.
How do i read HttpRequest data sent by POST method from client, on the server, in Dart?
I send a message from the client like this:
HttpRequest request = new HttpRequest();
var url = "http://127.0.0.1:8081";
request.open("POST", url, async: false);
String data = 'hello from client';
request.send(data);
On server i am catching the request like this:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
});
});
But i cant figure out how to actually read the data... There is not data property in HttpRequest nor anything else...
EDIT This is how i get the answer now:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
print("got it");
print(request.method);
if(request.method == "POST") {
print("got it 2");
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
print(postData);
});
}
});
});
But for some reason the request.method is not "POST" but "OPTIONS", and if i change to if(request.method == "OPTIONS") , then print(postData) will still return nothing...
You can use the StringDecoder to tranform from "List of Int" to "String" from the HttpRequest. Since no matter if you send json, plain text, or png, Dart always send data in form of
"List of Int" to the server.Another means is to use the Streams (http://www.dartlang.org/articles/feet-wet-streams/) tested on Heroku Steam v0.6.2 Dart Editor 0.4.3_r20602 Dat SDK 0.4.3.5_r26062
For example,
the client:
import 'dart:html';
import 'dart:json' as Json;
import 'dart:async';
import 'dart:uri';
final String data = 'Hello World!';
void _sendPNG(String pngData) {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_)
{
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
}
);
// POST the data to the server Async
print('Sending Photos to the server...');
var url = "/png";
request.open("POST", url);
request.setRequestHeader("Content-Type", "text/plain");
request.send(data);
}
the server:
import 'dart:io';
import 'dart:async';
import 'dart:json' as Json;
import "package:stream/stream.dart";
import 'package:xml/xml.dart' as xml;
import 'package:unittest/unittest.dart';
import 'package:rikulo_commons/mirrors.dart';
void receivePNG(HttpConnect connect){
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/png' && request.method == 'POST')
{
String png='';
response.write('The server received png request!');
//read incoming List<int> data from request and use StringDecoder to transform incoming data to string
var stream = request.transform(new StringDecoder());
stream.listen((value){
print(value);
//Hello World!
}
else
{
response.write('error');
response.statusCode = HttpStatus.NOT_FOUND;
connect.close();
}
}
configure.dart
var _mapping = {
"/": home,
"/png": receivePNG,
};
Right now, the handling of POST data is a little difficult. But essentially the HttpRequest itself has to be 'listened' to. HttpRequest is a stream itself. In particular it's a Stream<List<int>>. So basically your data may be passed to your HttpRequest as multiple List<int>'s. So we need to reconstruct the data then convert it into a string (assuming you're expecting a string, not binary data, etc). Here's more or less what I do:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
if(request.method == "POST") {
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
// Do something with the data now.
});
}
request.response.close();
});
Note that the request.listen(dataBody.AddAll, ...) basically calls List.addAll() each time data is to the server (in cases of larger data or multi-part forms it may not come all at once). This ensures we buffer it all until the stream indicates it is 'done' In which case we can now do something with the data we received, like convert it to a string.
I have found this useful example with client/side code
GitHub json send to server Example
// XXX: Dart Editor thinks this is OK, but I haven't run it.
import 'dart:html';
String encodeMap(Map data) {
return data.keys.map((k) {
return '${Uri.encodeComponent(k)}=${Uri.encodeComponent(data[k])}';
}).join('&');
}
loadEnd(HttpRequest request) {
if (request.status != 200) {
print('Uh oh, there was an error of ${request.status}');
return;
} else {
print('Data has been posted');
}
}
main() {
var dataUrl = '/registrations/create';
var data = {'dart': 'fun', 'editor': 'productive'};
var encodedData = encodeMap(data);
var httpRequest = new HttpRequest();
httpRequest.open('POST', dataUrl);
httpRequest.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
httpRequest.onLoadEnd.listen((e) => loadEnd(httpRequest));
httpRequest.send(encodedData);
}