RestSharp send proper value with header - asp.net-mvc

Please check the RestSharp code bellow. I am passing AddHeader correctly however i am getting response saying i am not passing Content-Type header correctly. How can i fix this issue any idea? Note: api documentation details here. Also checkout debug response screen shot bellow
static void Test()
{
var client = new RestClient("https://api.getresponse.com/v3");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Content-Type","application/json");
request.AddHeader("X-Auth-Token:", " api-key my-key-here");
request.Parameters.Clear();
var response = client.Execute(request);
}

Related

how to fix flutter web http error making http request to a particular web server

I am trying to make an HTTP request to 000webhost as below in my flutter web app. The first method is the same as the second, I only changed the URL. However, the first one works but the second does not work. Someone suggested adding more headers but I have no idea which headers to add.
// This method WORKS
getMethod()async{
print("IN GET ....");
String theUrl = 'https://jsonplaceholder.typicode.com/todos';
var res = await http.Client().get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
//var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
var responsBody = json.decode(res.body);
print(responsBody);
return responsBody;
}
// This DOES NOT WORK
getMethod()async{
print("IN GET ....");
String theUrl = 'https://funholidayshotels.000webhostapp.com/fetchData.php';
var res = await http.Client().get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
//var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
var responsBody = json.decode(res.body);
print(responsBody);
return responsBody;
}
After struggling with this for some time I figured out the problem was from the server side
I had to add Header add Access-Control-Allow-Origin "*" to .htaccess on 000webhost And This solves it for me
You can also Add the code below to your php file like so:
<?php
require('connection.php');
header("Access-Control-Allow-Origin: *");
....
code goes here
....
?>
I Tried this on LocalHost and it worked

Can I can return json list from HttpClientResponse

I am trying to connect with our server using dart and flutter. I get an error in certificate server, I get the code and I get response exactly, but the problem is the response keeps coming back as a string. I want it as a list to loop through it.
HttpClient client = new HttpClient();
client.badCertificateCallback =((X509Certificate cert, String host, int port) => true);
String url ='https://xxx';
//Map map = { "email" : "email" , "password" : "password"};
HttpClientRequest request = await client.getUrl(Uri.parse(url));
//request.headers.set('content-type', 'application/json');
//request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
I have simple code to get a JSON response as a list. The problem is our server is using https and nginx to take all request to the correct port. Previous code worked but I need to respond with a list.
simple code is :
String apiURL = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(apiURL);
return json.decode(response.body);
You won't get a list. You would get flat json which you would need to process. Processing can be done using simple script using powershell.

Image upload to server using dart, flutter

upload(File imageFile) async {
var uploadURL = "http://xxxxxx.org.xx/appdata/members/images";
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});}
But, it is throwing statuscode 301 and no file is uploaded to server's destination folder. what could be wrong?
The 301 HTTP code means that the server is trying to redirect you to another URL - see wikipedia's list of response codes.
I'd guess that your request has been redirected and the client isn't following... although MultipartRequest's followRedirects should be true by default you could try setting that explicitly, and you could increase maxRedirects.
I'd suggest testing out the API you're trying to use with curl (or similar) to make sure it's working as expected before trying with flutter.

Can't create account in aqueduct's db_and_auth/wildfire example

I have been trying to learn how to use Aqueduct's authorization but I am struggling with some errors.
I found this question (OAuth Error using Aqueduct, mismatched ManagedPropertyType), which solved the first error saying it was expecting a string while an _ImmutableList was being passed. Nevertheless, whenever I make a the following POST request:
Future main() async {
var http2 = new http.Client();
var clientID = "com.wildfire.mobile";
var clientSecret = "myspecialsecret ";
var body = "username=usr&password=pwd&grant_type=password";
var clientCredentials = new Base64Encoder().convert(
"$clientID:$clientSecret".codeUnits);
var response = await
http.post(
"http://localhost:8081/register",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic $clientCredentials"
},
body: body);
I get a 500 error as a response and the following exception:
NoSuchMethodError: The getter 'credentials' was called on null.
in
request.authorization.credentials.username
Nevertheless, in the _user table I see an entry for the user I registered. Should I juts ignore the error or is there someway to solve this issue?
Edit:
It was indeed a misconfiguration issue. After deleting all my databases, I added a database.yaml file, which I thought was the same as the config.yaml but apparently is not.
Credentials will be null if the request doesn't pass through an Authorizer. In this case, you'll want a basic authorizer:
router
.route("/register")
.pipe(new Authorizer.basic(authServer))
.generate(() => new RegisterController());

IdentityServer3 Response status code does not indicate success: 400 (Bad Request)

I always get Bad Request 400 from IdentityServer3. I am trying for 3 days now but no luck :( Anyone could please tell me what am I doing wrong?
I am trying to access IdentityServer3 hosted by another vendor that I have no control. The vendor has asked us to implement Implement OAuth2 authentication with Bearer token. The vendor provided us with the Client ID, Client Secret and the URL to be used is http://www.xxxxxx.com/identity/connect/token
The vendor told us to use to request bearer token and use it in the request headers Authorization: Bearer
I can successfully obtain the bearer token from vendor. But when I call the
GET /api/profiles/myemailaddress#gmail.com I get Bad Request 400
Here is what I have done:
TokenClient client = new TokenClient("http://www.xxxxxx.com/identity/connect/token", "myclientid", "myclientsecret", AuthenticationStyle.PostValues);
var response = await client.RequestResourceOwnerPasswordAsync("myemailaddress#gmail.com", "mypassword", "profile"); // successfully gives me the token
i got the access token, now i want to use the token to request user profile:
var clienthttp = new HttpClient();
clienthttp.BaseAddress = new Uri("http://www.xxxxxx.com");
clienthttp.SetBearerToken(response.AccessToken);
var json = await clienthttp.GetStringAsync("http://www.xxxxxx.com/api/profiles/myemailaddress#gmail.com"); // error Bad Request 400
Additional Info:
"scopes_supported":["profile","offline_access"],
"claims_supported":[]
Thank you.
The vendor was expecting additional value in the header. Since my request was missing that additional value, they returned Bad Request. I had to modify my code to find the exact reason of bad request.
Here is the updated code, might be useful for someone:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.xxxxx.com");
client.SetBearerToken(response.AccessToken);
var callApiResponse = client.GetAsync("api/profiles/myemailaddress#gmail.com").Result;
string tokenresponse = callApiResponse.StatusCode.ToString();
string clientresult = callApiResponse.Content.ReadAsStringAsync().Result;
tokenresponse: "Bad Request 400"
clientresult: "Missing CompanyID in the header"
Then I knew that they also expect companyid in the header so I added it. then all was good.
client.DefaultRequestHeaders.Add("CompID", "xxxxxx");
I had a similar error (Response status code does not indicate success: 400 (Bad Request)) for different resource not identity server. i manage to resolve that using FormUrlEncodedContent
Refer below code
using (HttpClient client = new HttpClient())
{
string baseUrl = "https://*******.com/****"
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "******");
jsonValues.Add("password", "******");
var contenta = new FormUrlEncodedContent(jsonValues);
var response = await client.PostAsync(baseUrl, contenta);
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
}
}

Resources