i am new to using curl and I am trying to execute a https post request using curl. and it doest seem to work like other json post requests so i was hoping someone can explain this to me
I am not sure if i understood your answer well enough but you can take a look at this Package or this one the latter one provides provides more flexibility and features like Interceptors etc.
You can use this package Curl https://pub.dev/packages/curl
example code
import 'package:curl/curl.dart';
import 'package:http/http.dart';
final req1 = new Request("GET", "https://exyui.com/endpoint");
print(toCurl(req1));
// will print out:
// curl 'https://exyui.com/endpoint' --compressed --insecure
final req2 = new Request("PUT", "https://exyui.com/endpoint");
req2.body = "This is the text of bodyš
, \\, \\\\, \\\\\\";
print(req2);
// will print out:
// curl 'https://exyui.com/endpoint' -X PUT -H 'content-type: text/plain; charset=utf-8' --data-binary \$'This is the text of body\\ud83d\\ude05, \\, \\\\, \\\\\\' --compressed --insecure
final req3 = new Request("POST", "https://exyui.com/endpoint");
final part1 = "This is the part one of content";
final part2 = "This is the part two of contentš
";
final expectQuery = "part1=This%20is%20the%20part%20one%20of%20content&part2=This%20is%20the%20part%20two%20of%20content%F0%9F%98%85";
req3.bodyFields = {
"part1": part1,
"part2": part2,
};
print(toCurl(req3));
Related
I'm learning how to fetch data using an API in R. I understand that the aim of httr is to provide a wrapper for the curl package.
The documentation I'm following so that I make requests to the API has the following HTTP request format. This code below will be used to generate a token
curl -s \
-d "client_id=clientidā \
-d "username=userā \
-d "password=pwdā \
-d "grant_type=password" \
-d "scope=openid email" \
"https://auth.com/token"
Afterward, I'll use the token to now communicate with the API using this request
curl --header "Content-Type: application/json" \
--header "Accept: application/+json" \
--header "Authorization: Bearer token_goes_hereā \
--request GET \
--url "https://api-sitename.org/sections?parent_id=0"
Initially, I run these two requests in a terminal and they were successful, I got a response in JSON format. My question is, how do I run these requests in an R script such that I get a responses and they're it's stored in R studio global environment? My goal is to finally load the dataset from the API to the Rstudio working environment.
T
Here is something to get you started:
library(httr)
resp <- POST("https://auth.com/token",
body=list(client_id="clientid",
username="user",
password="pwd",
grant_type="password",
scope="openid email")
)
#parse for auth token here
content(resp, "text")
get_resp <- GET("https://api-sitename.org/sections?parent_id=0",
add_headers("Content-Type"="application/json",
Accept="application/+json",
"Authorization"=paste("Bearer", token))
I was able to successfully get my API call in R by replacing the content in header to body.
Here is my code
#' Th base url
base_url <- "your/url/endpoint/for/token"
# base64 encoded client id, my end-point requires to encone the client id to base64
c_id <- RCurl::base64(txt = "clinetid:sceret", mode = "character")
#' headers
headers <- httr::add_headers(
"Authorization" = paste("Basic",c_id, sep = " ")
)
# move everything else to the body. grant_type and password were requested by the endpoint
body <- list(
username = "your username",
password = "your password",
grant_type = "password",
scope = "read"
)
#' post call to get the token
httr::POST(
url = base_url,
body = body,
config = headers,
httr::accept_json()
)
When I had the user name and password in the body, I received 400 and 403 errors. Once I moved them o the body received 200 status and the token was successfully retrieved. If you can provide what you tried in R, can help you troubleshoot.
I am trying to upload a file to a platform via an API
CUrl request from terminal works fine
curl -v --trace-ascii trace.txt -H "Authorization: Bearer XXXX-XXXX-XXXX-XXXX" -F "file=#test1234.txt;type=text/txt" https://xxx.YYYY/upload
But in R when I use the Post I get status 500 error
outfilename="/Volumes/Work/texttest.txt"
POST(url="https://xxx.YYYY/upload",body = upload_file(
path = outfilename,
type = 'text/txt'),
verbose(),add_headers(Authorization=paste0("Bearer ",btoken$access_token)))
or
postForm(uri="https://xxx.YYYY/upload",file = fileUpload(
filename = outfilename, contentType = 'text/txt'),
add_headers(Authorization=paste0("Bearer ",btoken$access_token)))
Can anyone help please ?
EDIT: Got it to work with postForm, will be great if someone helps on why it does not work with POST
httpheader <- c(Authorization=paste0("Bearer ",btoken$access_token))
status<-postForm(uri=paste0(server,"upload"),file = fileUpload(filename = outfilename),.opts=list(httpheader=httpheader))
For POST, the most similar translation is
POST(url="https://xxx.YYYY/upload",
body = list(file=upload_file(
path = outfilename,
type = 'text/txt')
),
verbose(),
add_headers(Authorization=paste0("Bearer XXXX-XXXX-XXXX-XXXX"))
)
Notice how the body= is a list. This submits the data as form-data which is what the curl -F option does.
Note that I find that using a site like http://requestb.in/ can make it easier to troubleshoot these problems. By posting to that site, you can see exactly what is sent to the server and see how the request different between the two methods.
I'm trying to learn Spring MVC and i'm stuck at this program behaving weirdly can any one please help.
#Controller
public class GreetingController {
#RequestMapping(value="/greeting", consumes={"application/json", "application/xml"},produces = {"application/json","application/xml"}, headers = "Content-type=*/*")
public #ResponseBody Greeting greeting(
#RequestParam(value="name", required=false, defaultValue="I'm default") String name) {
Greeting obj = new Greeting("1",name);
Address address = new Address("CA, US");
obj.setAddress(address);
return obj;
}
}
Greeting and Address are just POJO's.
here is the output from 'curl' i.e irrespective of Content-type output is in JSON format.
curl --header "Content-type: application/xml" http://host.com:8080/javamvc/greeting
{"id":1,"content":"Hello, I'm default!","address":{"addr":"CA, US"}}
curl --header "Content-type: application/json" http://host.com:8080/javamvc/greeting
{"id":1,"content":"Hello, I'm default!","address":{"addr":"CA, US"}}
and then when i use 'RestClient' from mozilla i get output as xml always as irrespective of my Content-type=application/json or Content-type=application/xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><greeting><id>1</id><content>Hello, I'm default!</content><address><addr>CA, US</addr></address></greeting>
Can anyone please help?
In your curl requests, you are specifying the Content-Type of the request body, not the content type you are expecting in the response body.
For that, you need to specify the Accept header.
Spring is always producing application/json, because it's the first in the list of produces values.
You'll have to be more specific about what you are doing with Mozilla, but it seems like it's requesting with the Accept header being application/xml.
Iām playing with GitHub web hooks and I want to use curl to post some sample JSON. The request is supposed to contain a payload POST parameter with the JSON string as a value. As an example, this works:
$ curl --form payload='{"foo":1}' http://somewhere
But I need to read the JSON from a file (say foo.json). Replacing the JSON string by #foo.json posts the payload in the request body:
--------------------------8d0c6d3f9cc7da97
Content-Disposition: form-data; name="payload"; filename="foo.json"
Content-Type: application/octet-stream
{'foo':1}
--------------------------8d0c6d3f9cc7da97--
Thatās not really what I want, I need the payload to be passed as a parameter. How do IĀ do that?
Maybe silly but try this:
cat foo.json | xargs -I % curl --form payload='%' http://example.com
Just wrote this little thing and it worked:
var=`cat some.json` && curl --form payload="$var" http://lvh.me/test/index.php
Hereās an alternative Perl testing script. Pass the target URL as the first argument, feed the JSON to STDIN:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP;
my $target = shift #ARGV or die "Need a target URL";
my $ua = LWP::UserAgent->new;
my $payload = do { local $/; <STDIN> };
my $response = $ua->post($target, { payload => $payload });
print $response->as_string;
I'm developing a basic application in Qt that retrieves data from Parse.com using the REST API. I went through some class references and the cURL manual but it's still not clear how you set the request parameters. For example, I'd like to authenticate a user. Here's the curl example provided by Parse:
curl -X GET \
-H "X-Parse-Application-Id: myappid" \
-H "X-Parse-REST-API-Key: myapikey" \
-G \
--data-urlencode 'username=test' \
--data-urlencode 'password=test' \
https://api.parse.com/1/login
I set the url and the headers like this
QUrl url("https://api.parse.com/1/login");
QNetworkRequest request(url);
request.setRawHeader("X-Parse-Application-Id", "myappid");
request.setRawHeader("X-Parse-REST-API-Key", "myapikey");
nam->get(request);
which worked fine when there were no parameters, but what should I use to achieve the same as curl does with the --data-urlencode switch?
Thanks for your time
Unfortunately, QUrl::addQueryItem() is deprecated in qt5 but starting from there I found the QUrlQuery class which has an addQueryItem() method and can produce a query string that is acceptable for QUrl's setQuery() method so it now looks like this and works fine:
QUrl url("https://api.parse.com/1/login");
QUrlQuery query;
query.addQueryItem("username", "test");
query.addQueryItem("password", "test");
url.setQuery(query.query());
QNetworkRequest request(url);
request.setRawHeader("X-Parse-Application-Id", "myappid");
request.setRawHeader("X-Parse-REST-API-Key", "myapikey");
nam->get(request);
Thanks for the tip Chris.
I believe QUrl::addQueryItem() is what you're looking for
QUrl url("https://api.parse.com/1/login");
url.addQueryItem("username", "test");
url.addQueryItem("password", "test");
...
Try to use QtCUrl. It's easy, if you are familiar with curl.
QtCUrl cUrl;
QUrl url("https://api.parse.com/1/login");
url.addEncodedQueryItem("username", "test");
url.addEncodedQueryItem("password", "test");
QtCUrl::Options opt;
opt[CURLOPT_URL] = url;
QStringList headers;
headers
<< "X-Parse-Application-Id: myappid"
<< "X-Parse-REST-API-Key: myapikey"
opt[CURLOPT_HTTPHEADER] = headers;
QString result = cUrl.exec(opt);