I want to build a protocol on top of http (like WebDAV). So it makes sense to use HttpURLConnection because it contains all basic methods, response codes and so on. Unfortunately it prevents setting other methods like:
HttpURLConnection con = URL.openConnection( "http://abc.def/someServlet" );
con.setRequestMethod( "MyMethod" );
throws a ProtocolException Invalid method MyMethod.
So I extended it and overwrote "setRequestMethod( String )" to accept "MyMethod". This does not work, because URL only returns a HttpURLConnection. Is there any way to use HttpURLConnection to accept other methods?
Please don't, I tell you this because I did the same error when I started programming in java and it did not pay off.
Ask yourself this question, will you ever pass the child class to a function / method / constructor which accepts the parent class?
For example will you put in a collection a mix of HttpURLConnection and MyServiceURLConnection.
If not so, you will be better off with a brand new class which uses a HttpURLConnection to provide the low level operations.
You might wish to consider RESTful interface. You still use http werbs but you are level up, don't see it, can do any interface, use factories, like:
public String readFileAsString(String url) {
String result = null;
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.type("text/plain").get(ClientResponse.class);
result= response.getEntity(String.class);
response.close();
} catch (Exception e) {
e.printStackTrace();
result = "";
}
return result;
}
url dosent return HTTPURLConnection , it returns URLConnection because you didnt cast it
so you cannot override the HTTPURlConnection method setRequestMethod()
Related
I'm learning web services using Java. I'm technically a noob, this is the code I've written, which works, I just don't know which method has what advantage over another, like which one is more secure? Which one will be more faster?
I'm not asking for complete too broad an answer. A short concise one will do.
I've created a REST service using Jersey 2.x and I've created client to consume the said REST service.
POST resource is as follows,
#POST
#Path("postactivity")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String createActivity(
#QueryParam("id") int id,
#QueryParam("description") String description,
#QueryParam("duration") int duration,
#QueryParam("name")String name)
{
//My code that creates Activity object from QueryParams is here.
}
Now I've created a Client which is a Java Application. I'm consume the above REST Service above in following two ways.
Method 1 Using HTTPURLConnection
private static void doPost(){
QueryString qs = new QueryString("id", "123"); //QueryString is a class created to build query, not important to the question.
qs.add("duration", "12");
qs.add("description", "This is description");
qs.add("name", "This is Name");
String url = "http://localhost:8080/webservices/webapi/activities/activity?" + qs;
URL obj;
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Type","application/json");
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla 5.0");
con.setDoOutput(true);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Activity activity = GSON.fromJson(response.toString(), Activity.class); //This is for checking if i'm getting correct data back which I'm sending.
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Method 2 Using WebTarget available via Jersey
private static void doPost(){
Response entity = webTarget
.path("activities/postactivity")
.queryParam("id",2204)
.queryParam("description","Foo")
.queryParam("duration",100)
.queryParam("name", "Bar")
.request()
.post(null);
String entityRead = entity.readEntity(String.class);
System.out.println(entityRead);
Activity activityRead = GSON.fromJson(entityRead, Activity.class);
}
Thanks.
Honestyl i have two things to write to you:
1. The HttpURLConnection is the Java personal way of doing a retrieve of a web affiliate (like web services) but you have a better and stress-free way of doing it with Jersey and this will make things faster and smoother for you. For some persons they even say that the Jersey style is the High-level API while the HttpURLConnection is called the low-level API.
2. Your question was able to provide me with a necessary solution to a problem i have had for the past two days with consuming a #Queryparam POST webmethod. I really appreciate this.
Thanks
I have a REStful webservice (java, jersey) to do some stuff.
every function that calls an ajax request (GET or POST) with an url to the REST controller works fine... except of the recent ones and I do not know why.. i tried everything and stuck with this problem for nearly three days (wrote 3 different functions, changed from GET to POST, rewrote the function with new pathannotiation, tried to call on pageload.. renamed everything), I realy appreciate ANYTHING that could help me...
if the url contains rest/* the controller forwards it to the class which implements the needed functions..
JS function
function testFunc() {
$.ajax({
url: "rest/name/wut",
type: "GET",
contentType: "application/json;charset=utf-8",
success: function(response) {
alert("LSKDFJLSDKJFLKSD " + response);
},
error: function(response) {
alert("ma oidaaaa " + JSON.stringify(response));
}
});
};
Java Code in the RESTClass...
#GET
#Path("/wut")
#Produces(MediaType.APPLICATION_JSON)
private String wut() {
JSONObject json = new JSONObject();
json.put("print", "wuut");
return json.toString();
}
It does not matter if the method is doing anything useful or not... it just returns 404 no element found.
(it is not even called) Therefore i tried different new methods in the RESTClass... like:
#GET
#Path("/wut")
#Produces(MediaType.APPLICATION_JSON)
private String wut() throws IOException {
URL url = new URL(url);
StringBuffer response = new StringBuffer();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
I am using this snipped in another method, which is working.. I replaced the real URL with "url" for posting btw.
I also tried different MediaTypes: WILDCARD, TEXT/PLAIN...
And to just return a String...
Anyone any ideas (and SORRY for the bad english, I am really desperate so i did not do a spellcheck and english is not my native :( )
Two ideas:
First, declare your wut() method as public: public String wut()
Second, try to call your method in a browser, for example http://localhost/rest/name/wut and see what happens
I would try to use an absolute path:
Change:
url: "rest/name/wut",
to
url: "/rest/name/wut",
The error message tells me that, your client did not try the address the server provides.
I am new to Jersey Java REST WebService framework. I am trying to write a service method which consumes and produces JSON. My service code is below. It is simplest code, just for studying purpose.
#Path("/myresource")
public class MyResource {
#Path("/sendReceiveJson")
#GET
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendReceiveJson(String name)
{
System.out.println("Value in name: " + name);
return "{\"serviceName\": \"Mr.Server\"}";
}
}
And following is JerseyClient code.
public class Program {
public static void main(String[] args) throws Exception{
String urlString="http://localhost:8080/MyWebService/webresources/myresource/sendReceiveJson";
URL url=new URL(urlString);
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("{\"clientName\": \"Mr.Client\"}");
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
But when i run service and then client, i am unable to send/receive JSON data. I get Exception at connection.getInputStream() which is
Server returned HTTP response code: 405 for URL: http://localhost:8080/hellointernet/webresources/myresource/sendReceiveJson
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
Please guide me, what needs to correct, or whether i am in wrong direction.
Your resource method is annotated as #GET which means any input data would have to be query string parameters.
In this context #Consumes(MediaType.APPLICATION_JSON) doesn't make a lot of sense as only APPLICATION_FORM_URLENCODED is supported via GET.
When you client calls setDoOutput(true) it probably switches your HTTP call to a POST hence causing the 405 Method Not Allowed.
If you want to consume JSON you should change your #GET annotation with #POST instead. Your client call should then work if it's indeed a POST. You can specify it with the following method:
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
This API is pretty low level though, so I'd highly recommend you use Jersey's Client API instead. See https://jersey.java.net/documentation/1.17/client-api.html
I just realized that it is possible to define something like this in my RESTful resource .java file:
#GET
#Produces("text/plain")
public String getPlainTextHello() { ... }
#GET
#Produces("application/json")
public String getJSONHello() { ... }
Isn't that fantastic? But wait the moment....
PROBLEM
I am consuming my API with simple client. Something like this code with help of HttpURLConnection:
URL obj = new URL("http://some.url/res/hello");
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
... /* get response ... conn.getInputStream() */
How the server 'know' which one method call to serve the client?
Regards.
First of all you should consider using the same method for different types of "produces":
#GET
#Produces({ "application/xml", "text/plain"})
public String getHello() { ... }
The different types of "produces" could be handled by JAXB (in case the response is an object...).
You can define the client side "accept" mime type by using:
String uri =
"http://localhost:8080/hello/";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
This question provides more insights (and other client side frameworks) related with this problem: REST. Jersey. How to programmatically choose what type to return: JSON or XML?
You'd probably want a generic function to do all the common work, and then simply pass this work to the response specific functions you outlined.
getHello(String responseType)
{
// do all your work you'd end up doing in both functions
switch (responseType):
case ("json") {
return getJSONHello(work);
}
case ("text") {
return getPlainTextHello(work);
}
}
I made some more checks on this and what works for me is just settings Accept:
...
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", mime);
...
where mime is "text/plain" or "application/json". This way my server calls one of the GET function.
Anyway I am confused why most answers suggest to use a common one function to serve a #GET and check for type inside this function...
My code is the consumer of an API (www.abc.com/public/news/apple.json). I get a json array in return which I then parse and populate in my own data structure. the code responsible for doing this is:
public Map<String,List<NewsItem>> populateNewsArray() throws Exception
{
url = domain + newsApiStr;
InputStream stream = getNews(url, true);
//jackson library object mapper
ObjectMapper mapper = new ObjectMapper();
//NewsApiObject class implements the structure of the json array returned.
List<NewsApiObject> mappedData = mapper.readValue(stream, NewsApiObject.class));
//populate the properties in a HashMap.
//return HashMap
}
public InputStream getNews(String request, boolean bulk) throws Exception
{
URL url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
return connection.getInputStream();
}
As you can see I am not the controller of the api, only the consumer. It is said that in unit tests, one is not suppose to make http requests. In this scenario, how can I unit test the populateNewsArray() function to see if the object mapping was correct (without any exceptions) and a valid hashmap was returned?
You should extract getNews() into a separate interface, e.g. NewsReader (although the word Reader has a specific meaning in the JDK, I like the name...)
public interface NewsReader {
InputStream getNews(String request, boolean bulk) throws Exception
}
Then implement that interface with using HttpURLConnection as per your code and update your code to allow injection of that particular interface. Then, if you need to test how your code handles an InputStream, you can create a mock of NewsReader which returns a InputStream with well-known content.
Remember to aim for high cohesion: your class shouldn't be an HTTP client and a stream parser.
I would create a subclass and overwrite the method getNews(...). In the subclass you then may return an InputStream for your test.
Since you should not depenend on some external file in a unit test and in order to get a better testable design I'd also change the getNews(...) method to return some kind of value which can be further processed by the mapper.