I want to send a http post request to the server (json format) and get a response back in json format using flutter and dart.
i have a code on C#, which is works
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://mysite");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"email\":\"no#no.ru\"," +
"\"password\":\"mypass\"," +"\"remember\":\"false\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.ReadLine(result.ToString());
}
and on php
$data = array(
'email' => 'no#no.ru',
'password' => 'mypass',
'remember' => 'false'
);
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
),
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
)
);
$url='https://mysite';
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode($result);
var_dump($response);
but on dart it doesn't works
var body = "{\"email\":\"no#no.ru\"," + "\"password\":\"mypass\"," +"\"remember\":\"false\"}";
var url =
Uri.https('mysite', '/mypath');
Map<String,String> headers = {
'Content-type' : 'application/json',
'Accept': 'application/json',
};
http.Response response = await http.post(
url,body:body,headers: headers);
print(response.body);
pubpecs.yaml:
http: ^0.13.0
i think the following error is caused by cors,but I can't solve it on the server side, as i written here
Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 906:28 get current
packages/http/src/browser_client.dart 71:22 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1613:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 155:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 707:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 736:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 533:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1219:7 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37307:58 <fn>
at Object.createErrorWithStack (http://localhost:57471/dart_sdk.js:5356:12)
at Object._rethrow (http://localhost:57471/dart_sdk.js:39475:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:57471/dart_sdk.js:39469:13)
at Object._microtaskLoop (http://localhost:57471/dart_sdk.js:39301:13)
at _startMicrotaskLoop (http://localhost:57471/dart_sdk.js:39307:13)
at http://localhost:57471/dart_sdk.js:34814:9
You have to escape your backslashes in your Json body, if that's the exact body you want to send:
var body = "{\\"email\":\\"no#no.ru\\"," + "\\"password\\":\\"mypass\\"," +"\\"remember\\":\\"false\\"}";
Related
When doing
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
The response is
)]}'
["uvresp","03AJpayVHarkP_b40i5...stuff...VOrIy6m3ws",1,120]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The )]}' breaks things. I have no idea where that is coming from.
$g_recaptcha_response looks fine to me (what I am sending to google to verify).
The function to verify recaptcha
function verify_recaptcha ($g_recaptcha_response, $remote_address) {
# Verify captcha
$post_data = http_build_query(
array(
'secret' => 'secret',
'response' => $g_recaptcha_response,
'remoteip' => $remote_address
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
return $result->success;
}
Thanks.
Ok my bad. The above code works, I had a problem further downstream (query was trying to use a column that did not exist).
How can i parse json data
data = "{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}"
I want to use token data
I tried like this code but not working..
Thanx to now
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json' );
//headers.append('Authorization' , 'Basic '+ btoa(tok));
let options = new RequestOptions({ headers: headers });
let postParams = {
username: this.uyelik['username'],
email:this.uyelik['email'],
password:this.uyelik['password']
}
this.http.post("https://deneme.com/api/v1.0/users/", postParams, options)
.subscribe(data => {
console.log(data['_body']);
this.veri = data['_body'];
this.veri = JSON.parse(this.veri);
console.log(this.veri['token']);
}, error => {
console.log(error);// Error getting the data
});
I SOLVED PROBLEM ;
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json' );
//headers.append('Authorization' , 'Basic '+ btoa(tok));
let options = new RequestOptions({ headers: headers });
let postParams = {
username: this.uyelik['username'],
email:this.uyelik['email'],
password:this.uyelik['password']
}
this.http.post("https://iothook.com/api/v1.0/users/", postParams, options)
.subscribe(data => {
//console.log(data['_body']);
veri = data['_body'];
veri= veri.slice(1, -1);
veri = veri.replace(/\\/g, "");
veri = JSON.parse(veri);
console.log(veri.token);
}, error => {
console.log(error);// Error getting the data
});
Try This.
this.http.post("https://deneme.com/api/v1.0/users/", postParams, options)
.map((res: Response) => res.json())
.subscribe(data => {
console.log(data['_body']);
this.veri = data['_body'];
this.veri = JSON.parse(this.veri);
console.log(this.veri['token']);
}, error => {
console.log(error);// Error getting the data
});
Parse like this-
var a = '{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}';
a.replace(/\//g, "");
var token = JSON.parse(a).token;
console.log(token)
i'm using in my symfony project Json data and in my controller i return data with New Response , it would be like :
{"cn":"dvsdvsdvergfe","gender":"M","fgff":"data","mail":"sino#hotmail.fr","sn":"SINO","uid":"sino"}
but if i return my data in a JsonResponse i have data like this format :
"{\"cn\":\"dvsdvsdvergfe\",\"gender\":\"M\",\"fgff\":\"data\",\"mail\":\"sino#hotmail.fr\",\"sn\":\"SINO\",\"uid\":\"sino\",
}"
the controller :
public function getUserByUidAction($uid)
{
$url = self::Ws_URL . self::Ws_PORT . self::Ws_GetUserByUID . $uid;
$headers = array() ;
$headers[] = "auth_token: ".self::Ws_Token ;
$headers[] = "Content-Type: application/json" ;
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
"http" =>array(
"method" => "GET",
"header" => "auth_token: ".self::Ws_Token
)
);
$response = file_get_contents($url, true, stream_context_create($arrContextOptions));
$viewHandler = $this->get('fos_rest.view_handler');
$view = View::create($response);
$view->setFormat('json');
return $viewHandler->handle($view);
return New Response($response) ;
}
what is happened ?
I am not getting the URL headers with a token in HTTP GET method and also GET method showing OPTION angular 2 typescripts.
Please help me.Thanks
Component.ts
onTestGet(Y)
{
var jwt = localStorage.getItem('id_token');
var k:string = localStorage.getItem(jwt);
var authHeader = new Headers();
authHeader.append('Content-Type', 'application/json');
if(k) {
authHeader.append('Authorization', 'Bearer ' + k);
}
return this._http.get('http://localhost:9095/api/v1/client/list?isClient=Y', {headers:authHeader})
.map(res => res.json())
.subscribe(
data => this.getData = JSON.stringify(data),
error => alert(error),
() => console.log("finished")
);
}
I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.
Problem is solved by moving second server to HTTPS...