How can I pass JSON data via HttpWebRequest - POST using VB.net? - asp.net

I've read a bunch of questions and tried a handful of different methods, so maybe my API service is just different. But this is my first time and I cant get it to work so I figured I'd post here and see if someone can educate me.
My code resulting in a response of error 400 - Bad request (API and other details changes for security)
Dim httpWebRequest = DirectCast(WebRequest.Create("https://api.smtp2go.com/v3/users/smtp/add"), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "POST"
Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
Dim json As String = "{'api_key': ""api-123456123456123456123456"", 'username': ""user#domain.com"", 'description': ""Generated via API"" }"
streamWriter.Write(json)
streamWriter.Close()
End Using
Dim httpResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
Dim result = streamReader.ReadToEnd()
End Using
Their example in JavaScript
var url = "https://api.smtp2go.com/v3/users/smtp/add";
$.ajax({
url: url,
method: 'POST',
headers: {
'Content-Type': "application/json"
},
data: JSON.stringify({
'api_key': "api-123456123456123456123456",
'username': "user#domain.com",
'description': "Generated via API"
}),
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
Their example in PHP
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json"
));
curl_setopt($curl, CURLOPT_URL,
"https://api.smtp2go.com/v3/users/smtp/add"
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array(
"api_key" => "api-123456123456123456123456",
"username" => "user#domain.com",
"description" => "Generated via API"
)));
$result = curl_exec($curl);
echo $result;

Related

Cannot convert data to json in angular 13 Content type 'text/plain;charset=UTF-8' not supported] after sending data from angular to .Net core Web Api

I am trying to connect a WebAPI build using .Net core 5
Web API: method
// POST api/<BusController>
//[EnableCors("AllowAllHeaders")]
[HttpPost]
public JsonResult Post([FromBody]BusRequest busRequest)
{
var result = "Response Text";
return new JsonResult(result);
//return result;
}
Angular 13 Code
const busRequest = {
"StartDate" : "02/15/2022",
"EndDate": "02/17/2022",
"BusNo" :null
};
**Approach 1:**
const header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded;application/json; charset=utf-8');
header.set('Accept','application/json');
const options = {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'}),
observe: 'response' as 'response',
responseType: 'json' as 'json',
body: busRequest};
this.http.request('post', 'http://localhost:55047/api/bus', options).subscribe();
**Approach 2:**
let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'});
this.http.post('http://localhost:55047/api/bus', JSON.stringify(Request), {headers: headers}).subscribe(data => {
console.log(data);
});
But nothing works.
Response is:
tatus: 415
title: "Unsupported Media Type"
traceId: "00-403257012c151a469a0e24b083d61d62-56ac63710daf8c45-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.13"
Did anyone faced the similar problem?

Goutte Scraping - JSON-LD - Only "#type":"Product"

I use Goutte to scrape JSON-LD data, like this:
$client = new Client();
$url = "https://www.xxxx.com";
$crawler = $client->request('GET', $url);
$crawler->filterXPath('//*[#type="application/ld+json"]')
->each(function ($node) {
//do something
}
Is it possible to filter such that it is only "#type": "product",
which gets run.
Thanks!

Firebase Dynamic Link CORS - XMLHttpRequest

I'd like to shorten my URL's using the Firebase Dynamic Link shortener. I followed the Rest API reference and the code seems to check out:
const url ="https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";
this.request = new XMLHttpRequest();
this.request.open("GET", url, true);
this.request.setRequestHeader("Content-Type", "application/json");
this.request.setRequestHeader("Access-Control-Allow-Origin", "*");
const parameters = {
"longDynamicLink": encodeURIComponent(window.location)
};
this.request.onreadystatechange = this.updateLink;
this.request.send(parameters);
But when I execute this code, I get a CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I can't seem to find a setting where I can enable Cross Origin Requests. Anyone who can tell me how to use Firebase Dynamic Links from the browser?
I solved this problem by just creating a PHP script that I can use to delegate the Firebase Rest call from client-side to server-side. This also ensures my users will never get to see my Firebase API key.
<?php
$LongDynamicLink = "MYHOST?" . urlencode($_GET["url"]);
$url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=MY_API_KEY";
$data = '{
"dynamicLinkInfo": {
"dynamicLinkDomain": "MY_LINK_DOMAIN",
"link": "' . $LongDynamicLink . '",
"androidInfo": {
"androidPackageName": "ANDROID_PACKAGE_NAME"
},
"iosInfo": {
"iosBundleId": "IOS_BUNDLE_NAME"
}
}
}';
echo httpPost($url, $data);
function httpPost($url, $data)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
?>
Using this code, you can call the PHP Rest API as such:
let request = new XMLHttpRequest();
request.open("GET", "MY_DOMAIN/?url=URL_I_WANT_TO_SHORTEN", true);
request.onreadystatechange = console.log(request.response);
request.send();

Angular 5 - HTTP post

I have a backend interface which I invoke with my Angular 1.3 application without problems. With my Angular 5 application I get an HTTP 403 (Forbidden)
I faced the request parameters in an picture (Angular 1.3 at the left side, Angular 5 at the right side):
My Angular 5 code looks like this:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
let options = new RequestOptions({ headers: headers });
return this.http.post(url, calendarEvent, options).map(res => res.json()).subscribe(res => console.log(res));
}
I have e.g. no idea why X-AUTH-TOKEN is not set with Angular 5 because I set it in the headers object with
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
and why OPTIONS is mentioned at Request Method with Angular 5 instead of POST like with angular 1.3.
Does anyone have any idea what I am doing wrong?
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(url, calendarEvent, Options).map(res => res.json()).subscribe(res => console.log(res));
OPTIONS request is considered as a pre-flight request, which is sent before the actual request to check the existence of method.
If the request sent is a valid one, it will call the valid method.
And regarding the request header, you can use the one in the above answer.
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
For Angular5,
import { HttpClient, HttpHeaders } from '#angular/common/http';
const headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
By default, 'Content-Type': 'application/json'
Stop using map.
Subscribe the response and store it to Observable for further access.
Example:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
return this.http.post(url, calendarEvent, {headers: headers}).subscribe(res => console.log(res));
}

Facebook apprequest error

Good day, everyone!
I have a problem with apprequests.
When i use Request Dialog, i have response with request id. Here is the code:
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script>
FB.init({appId:'400884386588720', xfbml:true, cookie:true});
var too = new Array('100003484704320');
function send() {
FB.ui({
method:'apprequests',
message:'http://wasm.ru',
to:too
}, function (response) {
var request = response.request;
var request_id = request + '_' + too[0];
console.log(request_id);
});
}
</script>
</body>
<input type="button" onclick="send(); return true;" value='Request'>
</html>
But user can't see this request! When facebook page refreshing, i can see notification, but after loading it disappears.
When i try use Graph Api, i have an error:
[error] => stdClass Object
(
[message] => (#200) All users in param ids must have accepted TOS
[type] => OAuthException
[code] => 200
)
Here is the code:
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $this->app_id.
"&client_secret=" . $this->secret .
"&grant_type=client_credentials";
$app_token = $this->request($token_url, 'POST');
$app_token = explode('=', $app_token);
$app_token = $app_token[1];
$message="Message with space and with link - http://wasm.ru";
$message = urlencode($message);
$url = 'https://graph.facebook.com/'.$user.'/apprequests?'.'message='.$message.'&access_token='.$app_token.'&method=post';
$res = $this->request($url, 'POST');
And the request function:
$ch = curl_init();
$options = array();
$options[CURLOPT_URL] = $url;
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_RETURNTRANSFER] = true;
if($method == 'get') {
$options[CURLOPT_HTTPGET] = true;
} else {
$options[CURLOPT_CUSTOMREQUEST]= 'POST';
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if($action == 'access_token'){
return $response;
}
$response = json_decode($response);
return $response;
I can't find error... Help!
Thanks.
The error message you receive ("All users in param ids must have accepted TOS") is because you are trying to send an app generated request to a user who is not connected to your app.
See the developer docs here https://developers.facebook.com/docs/requests/#app_to_user.
Requests sent with the request dialog and app generated requests are different and you can't use app generated requests to invite users to your app.

Resources