Java Client code to call restful web service - java

Can anybody tell me how to write a java client code to call restful web service with one parameter say email? I am trying the below code. But I am getting response as Success. Once this is success, I need the below XPHONE value. How to get this value?
XPHONE: 52-33-3669-7000
Here is the client code:
URL url = new URL("http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr=user.email");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Accept",
"application/json");
conn.connect();

I think you just missing response body handling.
There is nice article about rest-client code: article.

You can try using the JavaLite Http client:
JavaLite Http

Depends on how API is implemented value can be in response body or even in header, so this info you should know from specification or ask in dev team.
First try to check if everything works fine using CURL or better "Advanced rest client" ( its extension in Chrome browser) if it works, than just transfer flow to your code. How to use advanced rest client look here

Related

Is there any way to integrate coinbase with java?

I was using below code to get the response but I Was getting the 403 error
URL url = new URL ("https://api.commerce.coinbase.com/checkouts");
Map map=new HashMap();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
From https://commerce.coinbase.com/docs/api/
Most requests to the Commerce API must be authenticated with an API
key. You can create an API key in your Settings page after creating a
Coinbase Commerce account.
You would need to provide minimal set of information to API in order for it to respond back with success code 200.
Yes, but it looks like you aren't providing enough information. There are two header fields that need to be supplied as well. These are X-CC-Api-Key which is your API key and X-CC-Version. See the link below.
https://commerce.coinbase.com/docs/api/#introduction
Header fields can be provided to HttpURLConnection using the addRequestProperty
https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#addRequestProperty-java.lang.String-java.lang.String-
URL url = new URL("https://api.commerce.coinbase.com/checkouts");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.addRequestProperty("X-CC-Api-Key", "YourSuperFancyAPIKey");
connection.addRequestProperty("X-CC-Version", "2018-03-22");
connection.setDoOutput(true);
You also want to be careful about what method you use. You are supplying a POST method in your example. This probably not what you want to start with. If you send a GET method you will receive back a list of all checks. This will be a good place to start.
https://commerce.coinbase.com/docs/api/#checkouts
GET to retrieve a list of checkouts
POST to create a new checkout
PUT to update a checkout
DELETE to delete a checkout
This type of API is known as REST.

RESTFUL jetty service returning 403 error java

I am facing this HTTP 403 Forbidden response from a https REST service when I am trying to call it from my java code. Can you kindly let me know if I am missing something here?
Please note that the server returns the expected data when I trigger the request from any browser / SOAPUI/ Chrome Postman clients.
2 peer certificates are used - as shown in the ssl info from soapui after the request is sent.
The code snippet is attached. [The headers I set in the code are taken from the request header I found from the successful requests]
HttpsURLConnection connection = (HttpsURLConnection)new URL("https://server address").openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
connection.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1");
connection.addRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("Cache-Control","no-cache");
connection.setRequestMethod("GET");
connection.connect();
System.out.println("Response Code : " + connection.getResponseCode()+" "+connection.getResponseMessage());
Response Code : 403 Forbidden
Can you please check the Server URL if it is in the Java Acceptable format?
Sometimes java need escape characters to recognize strings correctly.
This question: What are all the escape characters? , can help you to check if you are using any of those characters. Also check if the conversion in the function is done properly.
Also, if you have more complex URL, consider to use java.net.URL .
Finally, check the user agent parameter Setting user agent of a java URLConnection .
Thanks for your response. The issue is with session cookie to be used for the connection. We are able to connect and get the response back with response code HTTP 200 once the cookie with JSESSIONID is passed as a header. Thanks again.

Getting HTTP response code in Java

I need to find the HTTP response code of URLs in java. I know this can be done using URL & HTTPURLConnection API and have gone through previous questions like this
and this.
I need to do this on around 2000 links so speed is the most required attribute and among those I already have crawled 150-250 pages using crawler4j and don't know a way to get code from this library (due to which I will have to make connection on those links again with another library to find the response code).
In Crawler4J, the class WebCrawler has a method handlePageStatusCode, which is exactly what you are looking for and what you would also have found if you had looked for it. Override it and be happy.
The answer behind your first link contains everything you need:
How to get HTTP response code for a URL in Java?
URL url = new URL("http://google.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
The response code is the HTTP code returned by the server.

java HttpUrlConnection POST: need to ask for a response for the POST to be committed?

I'm trying to post data on a server using java HttpUrlConnection class. It seems that if I somehow read the response of the server, the post works fine, but if I don't, the information is never posted.
This kind of behaviour is not mentionned in the HttpUrlConnection doc and all examples I've seen of HttUrlConnection ask for a response from the server.
I want to know if I made a mistake in my code or if this is a normal behaviour of HttpUrlConnection, and if it's the case, can someone with a better understanding of how this class works explain to me why it's so?
Thanks a lot!
Here is the code, the commented line is the one that makes the POST either work or fail:
URL url=new URL("myUrl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("Host", "myHost");
connection.setDoOutput(true);
os.write(staffToPost.getBytes("utf-8"));
os.flush();
os.close();
//System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
The URLCOnnection class needs a complete handshake for a POST to occur.This means, once you open a connection, you have to readback the response for the POST to actually take place.
You can explicitly call URLConnection.connect() or get any information about the HTTP response such as HttpURLConnection.getResponseCode etc to trigger HTTP request.
You should go through this comprehensive post on How to use java.net.URLConnection to fire and handle HTTP requests for better understanding.

Trying to GET a Google Spreadsheet in Java is returning HTTP error 405

Been working on this all day and have gotten no where with it.
My Java code looks like this:
final URL url = new URL(String.format("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=tsv&gid=0", spreadsheetId));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + wiseAuth.getAuthToken());
conn.setRequestProperty("GData-Version", "3.0");
conn.setRequestMethod("GET");
conn.setDoOutput(true); // trouble here, see below
conn.setInstanceFollowRedirects(true);
conn.connect();
I always get a FileNotFound error when attempting to do conn.getInputStream(). I narrowed it down to being that the response code is 405 Method Not Allowed. The exception is returning me my URL and I can access the page just fine in my browser.
It was then that I discovered that setDoOutput(true) executes a POST internally. But if I remove that line, conn.getInputStream() is null, and conn.getOutputStream() appears to return nothing--though maybe I am setting it up wrong?
I don't recommend you to do it like this, even if you get it working now you cannot ensure you will get it working in the future if Google started changing it.
Instead, consider using Google Spreadsheet API. The provided Java examples are pretty straightforward and you should able to accomplish what you want.
I would recommend using a web debugger like Fiddler to see what exactly your application is sending in the GET request and compare it to your browser. You might be missing an important header or something, and Fiddler makes it really easy to slowly strip down your browser's request to the essential elements (just drag a request to clone it, then take out headers).

Categories

Resources