Get JSON with Http status codes - java

I'm migrating a project from PHP to Java.
I had no problem doing this, but the project contains a HTTP request which I couldn't set up yet. It has to grab a JSON from an API (Authorisation required) and then save it as a variable (which gets passed on to my parser class).
This is the code I've used in php:
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'Accept: application/json' . "\r\n"
. 'Authorization: Bearer ' . $token . "\r\n",
),
)));
$url is the request url and $token the authorisation for the API.
I've already tried a couple of solutions and libraries from StackOverflow, but couldn't get any of these to work in the Java Version. Also I haven't found code which includes the response code, which would actually allow the program to notify the user what went wrong.
Update: I've tried to use the libery linked in the comments, but encoding the url just doesn't work, I get a java.io.UnsupportedEncodingException:
String url = URLEncoder.encode(requestURL,"UTF-8");
I also tried:
Url url = URLEncoder.encode(requestURL,"UTF-8");
which resulted in the same error.
Documentation doesn't help to fix this. Can someone explain what I'm doing wrong or give me some example code?

Related

CS CART API Login Post URL

There is an auth attribute having 2 parameters, but it didn't work
http://example.com/api/auth?email=example#gmail.com
The output of the URL is
{
"message": "Method Not Allowed: Missing parameters",
"status": 405
}
Also, the redirection_url parameter is not working.
Please help me fix this.
You need to provide
Auth Email
Auth Password
in Basic Oth in Postman
How do your make this call, via CURL I guesss?
You need to provide user's email and API KEY generated for this user, base64 encoded.
For example you could have:
$user = "test#example.com";
$api = "api_generated_through_edit_user";
$base64 = base64_encode($user.":".$api);
having this piece of code, you could add it to the CURLOPT_HTTPHEADER of your CURL request, like so:
...
...
CURLOPT_HTTPHEADER => array(
"Authorization: Basic " $base64 ,
"Content-Type: application/json",
"cache-control: no-cache"
),
...
...
You may also want to take a look here:
https://forum.cs-cart.com/topic/55511-update-product-via-rest-api/
Last but not least, where do you want to make the redirect?
For eaxmple, you could have sothing like this:
return array(CONTROLLER_STATUS_OK, "products.manage");

PHP; get post string from external url (JAVA)

I need to send string data to an external url which is an API for clients, but I always get the server sending back an error, and then I checked the log in the server which is written in JAVA, it throws an exception
"java.lang.NumberFormatException: For input string: "{"success":false,"errorCode":"500","message":"Unknown Error!","value":null,"totalPageCount":0,"footerValue":null}"
and here's my piece of php code:
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $params
),
));
$received = file_get_contents(URL, false, $context);
echo $received.'<br>';
I'm pretty sure the data I send to the server is in correct format as I have the access to the log, and I know that all response parameters from the server are in JSON, UTF-8 and post method, is there something I missed?
If more information needed please let me know, thanks.
You need to parse the string. You are getting NumberFormatException and this is because your server is receiving data which is not a numeric.
Integer.parseInt() // in java
You can parse the content in server side this way or send numeric data.
Another method:
Integer.valueOf() // in java

Send binary data from nodejs (request) to java (ZipInputStream)

For some reason zip files produced on nodeJS gets rejected on a Java server where you can only use "binary" data upload.
If I post the file with Postman using binary it works fine, but when sending through nodeJS (request/request-promise/http ...etc) it does not work.
It gives:
java.util.zip.ZipException: only DEFLATED entries can have EXT descriptor
at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:310)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:122)
at com.ws...
The files are valid (it accepts via postman!)
Spent nearly two days on this issue. Read through tons on stack overflow post (most of them did not have proper answer in this specific topic) and googled around, but all the efforts in vain.
I kept experimenting and the only solution which seemed to work just fine is using child process and curl...
In case someone else falls into this really annoying problem:
var exec = require('child_process').exec;
var args = "-X POST \
https://mywebsite.com/zip-upload \
-H 'Authorization: Bearer gFChWxzeCIZVLM2q...WlvDB6zq2uOHfUcdX' \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/zip' \
--data-binary #./data.zip";
exec('curl ' + args, function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
In my opinion, child_process is the last choice. If you have tried request or request-promise and failed, how about trying htp:
const htp = require('htp');
htp.post(
"https://mywebsite.com/zip-upload",
{ "Authorization" : "earer gFChWxzeCIZVLM2q...WlvDB6zq2uOHfUcdX"
, "Cache-Control" : "no-cache"
, "Content-Type" : "application/zip"
},
fs.createReadStream("./data.zip")
)
.then(function(response) { /* ... */ })
.catch(function(error) { /* ... */ })
;
I was facing similar problem. In my case, I was using custom value for Content-Type (e.g. - "application/abc+json") to upload a zip file via POST request in fetch(). It was working in Postman, but not in nodejs server.
I was able to get it working by adding Content-Length as header before making request via fetch().
Request headers I used - Content-Type, Content-Length, Authorization, and bunch of other API specific headers.
Hopefully this helps anyone facing issue.

How to send parameters in a GET call with restlet?

Confirmed the following in Curl:
This is working fine-
curl -X GET 'http://remoteUrl.com:8080/public/private/request/data?begin=12&end=20'
This is not working-
curl -X GET http://remoteUrl.com:8080/public/private/request/data?begin=12&end=20
So the whole purpose is to use the way first curl command in a java code with restlet to send the paramters in a GET request but unfortunately my code is not working.
Code:
ClientResource clientResource = new
ClientResource("http://remoteUrl.com:8080/public/private/request/
data?begin=12&end=20");
Representation clientText = clientResource.get();
Error Log:
INFO: Unable to read a header
java.io.IOException: Parameter or extension has no name. Please check your value
at org.restlet.engine.header.HeaderReader.readNamedValue(HeaderReader.java:499)
at org.restlet.engine.header.CacheDirectiveReader.readValue(CacheDirectiveReader.java:65)
at org.restlet.engine.header.CacheDirectiveReader.readValue(CacheDirectiveReader.java:38)
at org.restlet.engine.header.HeaderReader.addValues(HeaderReader.java:282)
at org.restlet.engine.header.CacheDirectiveReader.addValues(CacheDirectiveReader.java:50)
at org.restlet.engine.header.HeaderUtils.copyResponseTransportHeaders(HeaderUtils.java:776)
at org.restlet.engine.adapter.ClientAdapter.readResponseHeaders(ClientAdapter.java:129)
at org.restlet.engine.adapter.ClientAdapter.updateResponse(ClientAdapter.java:191)
at org.restlet.engine.adapter.ClientAdapter.commit(ClientAdapter.java:105)
at org.restlet.engine.adapter.HttpClientHelper.handle(HttpClientHelper.java:119)
at org.restlet.Client.handle(Client.java:153)
From the exception you give in your question, it seems that the value of the header Cache-Control isn't correct within the response. Restlet isn't able to parse it.
I guess that the value of this header is an empty string in the response...
Could you give us in your question the exact content of the response (mainly headers)?
Hope it helps you,
Thierry

PHP post data not being set calling Java Rest Web Service

I know there are a lot of questions related to this issue, but I'm facing an specific requirement for this purpose of posting data from PHP to a Rest Web Service. The details are explained above, but in summary, when I post data to a url (REST WS) and set the CURLOPT_POSTFIELDS the data is not being added to the request.
The scenario: I have a lot of Java Web Services (REST) running as modules, for example, I have a fileUploadModule which is a REST, I have a databaseModule which is another rest and finally a SearchModule, which is another REST.
I can invoke them directly my rest modules using a link like:
http://[MY IP]:8020/system.file.ws.module.ModuleFile/getResults/jsonp?fileName=fileName
http://[MY IP]:8021/system.search.ws.module.ModuleSearch/getResults/jsonp?xmlQuery=myXml
For the case of files and database, the programmer that was managing the code before me used gwt that connected to the module through a proxy; for instance:
http://[MY_PROXY_IP]:8013/system.file.ws.module.ModuleFile/getResults/jsonp?fileName=fileName
and in my proxy I can print the value of the request received, in this case I use a GET and I can print the request as:
GET /system.file.ws.module.ModuleFile/getResults/jsonp?fileName=idc1&folderType=campaign&callback=__gwt_jsonp__.P0.onSuccess&failureCallback=__gwt_jsonp__.P0.onFailure HTTP/1.1
. Now I am responsible for search that should run through PHP. I tested the url directly to the module and it works, but if I try to it by a proxy it does not seems to be working, it reach my proxy but when I print the request it is incomplete:
POST /system.search.ws.module.ModuleSearch/getResults HTTP/1.1
and I am supposed to receive something like the module file, I share my php code, all seems to be ok, but I don't know what can I be doing wrong... when I set the parameters in CURLOPT_POSTFIELDS the string is not being set
$url = "http://192.168.3.41:8013/system.search.ws.module.ModuleSearch/getResults";
try {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
$rawXml = $_POST['rawXml'];
$rawXml = str_replace("%", "%25", $rawXml);
$rawXml = str_replace("&", "%26", $rawXml);
$rawXml = str_replace("=", "%3D", $rawXml);
echo $rawXml;
curl_setopt ($ch, CURLOPT_POSTFIELDS,'xmlQuery='.$rawXml);
$info = curl_exec ($ch);
curl_close ($ch);
echo $info;
} catch (Exception $e){
echo $e->getMessage();
}
please I would really appreciate your help or observations. Than you very much in advance.
After long time, I saw this without an answer. I discovered the fail of this some time ago. This issue occurred because, when reaching server side, for some reason a batch file I did not noiced was adding an additional line to my content, and whenever I read the request content with my proxies, I used a "\n" delimiter, I mean, I have been reading my data using as the EOF indicator a line jump, that's why the content was never shown. I had to modify the code inside my proxy to allow reading the request until the end, not when finding a "\n" character. I mean, the content of the post was set in every case, but a batch process was corrupting that data. So thata was the issue, I just solved it by making sure that my reader always read my entire file considering even line jumps and white lines.
Regards.

Categories

Resources