I am using the bellow code to retrieve data from an API:
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=> "Cookie: JSESSIONID=CF0D1FA323B4F3FCEF90BA3EE4651CAC\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://webfeeder.cedrofinances.com.br/services/quotes/quote/vale5', false, $context);
The above code returns the following error message:
Warning: file_get_contents(http://webfeeder.cedrofinances.com.br/services/quotes/quote/vale5): failed to open stream: HTTP request failed! HTTP/1.1 405 Method Not Allowed in
The API uses REST (HTTP). The above method is describe as GET on documentation.
I've also tried to use PHP CURL. But the same error message is shown.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://webfeeder.cedrofinances.com.br/services/quotes/quote/vale5",
CURLOPT_HTTPHEADER => array("Cookie: JSESSIONID=CF0D1FA323B4F3FCEF90BA3EE4651CAC"),
));
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
The API documentation shows the following JAVA code to retrieve this same data:
public void getQuote(){
GetMethod getMethod = new GetMethod ("http://webfeeder.cedrofinances.com.br/services/quotes/quote/vale5");
String result = HttpUtils.get(getMethod);
System.out.println(resutl);
}
Related
Im trying to use Jsoup to make http Get request Discord Api, to get users information like this, what am I doing wrong ?
thread {
val id = "MY_ID:"
val token = "MY_TOKEN_BOT"
val source = Jsoup.connect("https://discord.com/api/v9/users/${id}")
.header("Authorization","Bot $token")
.ignoreContentType(true)
.method(Connection.Method.GET)
.execute()
.body()
runOnUiThread {
binding.txv.text = JSONObject(source).toString()
}
}
Response code GET 403
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=[https://discord.com/api/v9/users/264097054047862794]
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:890)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:829)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:366)
at com.example.jsouptester.MainActivity$testing$1.invoke(MainActivity.kt:80)
at com.example.jsouptester.MainActivity$testing$1.invoke(MainActivity.kt:62)
at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
i have created an api in java that accepts (name="sample" multipart[]) and when i'm requesting from php curl,
curl file objects in the array overwrites the old one to new, it means, only one value in the array is accepted.
This is one of the code that i tried:
$files = array(
'path/sample1.png',
'path/sample2.png',
);
$postfields = array();
foreach ($files as $index => $file) {
if (function_exists('curl_file_create')) {
$file = new CURLFILE(realpath($file), mime_content_type($file), basename($file));
}
else {
$file = '#' . realpath($file);
}
$postfields["sample"] = $file;
}
Note: I already tried sending a request in postman and it works perfectly with same keyname. The generated code have the same keyname in the post fields like this..
"sample" => "",
"sample" => ""
I don't know what to follow since the postman request is success, i tried also using the generated code from postman but the output is the same as stated above.
CURL:
CURLOPT_HEADER => 0,
CURLOPT_VERBOSE => 0,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SAFE_UPLOAD => true,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
this is my first question to this great community, so please have mercy.
I currently have following problem:
I want to recieve data from Bosch IoT API, but even following their documentation (https://bosch-iot-insights.com/static-contents/docu/html/Java.html >> Synchronous query execution - Example) didnt help me.
My code looks exactly the same as theirs:
String resourceUrl = "https://bosch-iot-insights.com/mongodb-query-service/v2/my-project";
String username = "my-user";
String password = "my-pw";
String authorizationCredentials = generateAuthorizationToken( username, password );
String payload = new String(Files.readAllBytes(Paths.get("C:/Users/my-name/Desktop/payload.json")));
String contentType = "application/json";
WebResource service = Client.create().resource( resourceUrl );
ClientResponse response = service.header( "Authorization", authorizationCredentials )
.header( "Content-Type", contentType )
.post( ClientResponse.class, payload );
System.out.println( response );
if ( response.getStatus() == 200 ) {
System.out.println( parseJson( response.getEntity( String.class ) ) );
}
I've also tried some solutions with C# and PHP, but they all had the same output: 403 Forbidden
When I am opening the project URL I can normally log in, but then I get obviously a 405 Method not allowed - Error, because there is no GET-Method.
I even contacted them and asked for help, but with my credentials they were getting following result:
POST https://bosch-iot-insights.com/mongodb-query-service/v2/my-project/execute-aggregation-query returned a response status of 200 OK
[
{
"key": value
}
]
I know what the Status Code 403 means, but even Bosch can't help me in this problem, because for them everything looked fine..
I'd appreciate and be very grateful if someone could help me or give me some ideas why this error is being produced.
(For more information feel free to ask!)
I am trying to send json data from my php file using a REST API which is developed in java to store data into database.
This is my code.
$p_name = $_POST['p_name'];
$tick = $_POST['tick'];
$url3 = 'http://myipaddress:port/myurl/';
$cookie_file =dirname(__FILE__).'\cookiefile.txt';
$form_data = array(
'p_name' => $p_name,
'tick' => $tick
);
$str = json_encode($form_data);
$ch = curl_init($url3);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch,CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: '.strlen($str)
) );
// set cookie
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
// use cookie
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
$response3 = curl_exec($ch);
}
$responseHTTP = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result3 = json_decode($response3);
var_dump($responseHTTP);
This is the code of java section.
#POST
#Path("/mypath")
#Produces("application/json")
#Consumes("application/json")
public String savePortFolioRecords(MyObject list_myobject){
String return_string=null;
try{
mydataManager dataManager=new mydataManager();
dataManager.setup();
dataManager.insertRecordsApi(list_myobject);
dataManager.exit();
Gson gson=new Gson();
return_string=gson.toJson("successfully insert the data");
}catch (Exception e) {
// TODO: handle exception
System.out.println("Giving Exception due to: "+e);
}
return return_string;
}
While i am testing the API using postman, it works perfectly and insert data into database, but in response box shows a text like Unexpected 's' .
But while i am trying to send value from my php file using curl, it does not store data into database. I don't understand whether my function in php
does not send data or can't receive json data in java section.
Moreover, when i am using CURLINFO_HTTP_CODE and print the corresponding response using var_dump, it shows int(404).
I have followed these links to solve my problem, but can't get any solution.
cuRL returnin 404 error
https://stackoverflow.com/questions/17476828/curl-returns-404-while-the-page-is-found-in-browser
https://davidwalsh.name/curl-post
Can any one tell me what's the problem here? I can't understand whether it is problem in my php file or in the java file.
I am studying vertx.io web client and I am already blocked doing a simple get... Uff. Here is what I put together (I am very new at vertx.io):
private void getUserEmail(String accessToken, Handler<AsyncResult<String>> handler) {
String url = "https://graph.facebook.com/me";
HttpRequest<JsonObject> req = webClient.get(url).as(BodyCodec.jsonObject());
req.addQueryParam("access_token", accessToken);
req.addQueryParam("fields", "name,email");
MultiMap headers = req.headers();
headers.set("Accept", "application/json");
req.send(h -> {
if (h.succeeded()) {
log.info(h.result().toString());
handler.handle(new FutureFactoryImpl().succeededFuture(h.result().bodyAsString()));
} else {
log.error(h.cause());
handler.handle(new FutureFactoryImpl().failedFuture(h.cause()));
}
});
}
I think it should be enought but instead it's not. When I send request I get this error back:
io.vertx.core.json.DecodeException: Failed to decode: Unrecognized token 'Not': was expecting 'null', 'true', 'false' or NaN
at [Source: Not Found; line: 1, column: 4]
Of course if I do the same get by browser I get the expected data. I read the tutorial and examined the examples, what am I missing?
You're receiving a 404 error with the body: Not Found and the codec tries to parse it as JSON and fails. You need to verify if the request you're sending is correct.