How to build RESTful request over in java - java

I tried to understand how to send REST request to server. If I have to implement this as a request in java using httpconnections or any other connections, how would I do that?
POST /resource/1
Host: myownHost
DATE: date
Content-Type: some standard type
How should this be structured in a standard way?
URL url= new URL("http://myownHost/resource/1");
HttpsURLConnection connect= (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Host", "myOwnHost");
connect.setRequestProperty("Date","03:14:15 03:14:15 GMT");
connect.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

There are many options, Apache HTTP client (http://hc.apache.org/httpcomponents-client-4.4.x/index.html) is one of them (and makes things very easy)
Creating REST requests can be as easy as this (using JSON in this case):
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/RESTfulExample/json/product/get");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
Update: Sorry the link to the documentation was updated.Posted the new one.

you should use json here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://myownHost/resource/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"DATE\":\"03:14:15 03:14:15 GMT\",\"host\":\"myownhost\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
more over it browse link

There are several ways to call a RESTful service with Java but it's not required to use raw level APIs ;-)
It exists some RESTful frameworks like Restlet or JAX-RS. They address both client and server side and aim to hide the technical plumbing of such calls. Here is a sample of code describing how to do your processing with Restlet and a JSON parser:
JSONObject jsonObj = new JSONObject();
jsonObj.put("host", "...");
ClientResource cr = new Client("http://myownHost/resource/1");
cr.post(new JsonRepresentation(jsonObject);
// In the case of form
// Form form = new Form ();
// form.set("host", "...");
// cr.post(form);
You can notice that in the previous snippet, headers Content-type, Date are automatically set for you based on what you sent (form, JSON, ...)
Otherwise a small remark, to add an element you should use a method POST on the element list resource (http://myownHost/resources/) or a method PUT if you have the unique identifier you want to use to identify it (http://myownHost/resources/1). This link could be useful to you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Hope it helps you,
Thierry

Related

HTTPS Request with SOAP Web Service

Hello I'm wondering how could I make a https request for soap API.
In Android app, I had searched a lot but there isn't clear tutorial explaining how to do that.
Any suggestion or help please?
Thanks
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class HttpsClient {
public static void main(String[] args) throws Exception {
String httpsURL = "https://postman-echo.com/post";
URL myUrl = new URL(httpsURL);
HttpURLConnection conn = (HttpsURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.append("<xml><body>your SAOP request here</body></xml>");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
System.out.println("Response code is : "+conn.getResponseCode());
System.out.print("Response text is :");
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
out.flush();
out.close();
br.close();
}
}
SOAP request is also an http POST with an xml in the request body. You need to change the url to the web service endpoint url and replace the sample string with your SOAP request.

The method DataOutputStream(OutputStream) is undefined for the type

I followed a lot of tutorials to make progress with this project. Now I am following a tutorial to create a Google cloud messaging server using JSON and Jackson library.
I somehow got the right Jackson library of all the libraries on the internet. But an error appeared which is the title of this question.
This is that code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.codehaus.jackson.map.ObjectMapper;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
//1. url
URL url = new URL("https://android.googleapis.com/gcm/send");
//2. open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3. specify POST method
conn.setRequestMethod("POST");
//4.set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
//5. add json data into POST request body
//5.1 use jackson object mapper to convert contnet object into JSON
ObjectMapper mapper = new ObjectMapper();
//5.2 get connection stream
DataOutputStream wr = DataOutputStream(conn.getOutputStream());
//5.3 copy content "JSON" into
mapper.writeValue(wr, content);
//5.4 send the request
wr.flush();
//5.5
wr.close();
//6. get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL: "+url);
System.out.println("Response Code: "+responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}
in.close();
//7. print result
System.out.println(response.toString());
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
I don't know how to fix this one, I've looked for answers but there isn't any answer.
your are missing new keyword
//5.2 get connection stream
DataOutputStream wr = DataOutputStream(conn.getOutputStream());
replace with
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

A simple JaxWS Rest that accept JSON Object

i'm trying to develop in Java a Rest WebService (i'm using RestEasy) that accept a generic JSonObject (i'm using JSON Simple 1.1.1).
What I've done so far:
#Path("/message")
public class TestRestService {
#POST
#Path("/{param}")
#Consumes("application/json")
public Response printMessage(JSONObject inputJsonObj) {
String result = "Restful example : " + inputJsonObj;
System.out.println(result);
return Response.status(200).entity(result).build();
}
}
And this is my client:
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/myProject/rest/message/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) { }
catch (IOException e) { }
}
Unfortunately i'm getting a 405 error, which means the path i suppose doesn't exist...
Can anybody help me?
thanks!
It seems like you are missing the /{param}-part of your Path. Right now you have nothing following the part from /message but your webserver can not find a method which accepts just the pass to /message. Since you are not trying to use the /{param} in your method i would suggest you just remove the #Path-Annotation from your method. This is possible because the Framework will just try and use the #Path annotation on the next level (here this is your class-level and this would be your /message path) with the HTTP-method annotated to your method. If the /{param} should be an optional parameter i would suggest using the #QueryParameter annotation in your method-head. For further information on this annotation you should read the docs for the javax.ws.rs framework.
Kind regards

C2DM java example of third-part app

I'm trying to do example form: http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html
I've got everything allright with android app (I think), but to simulate the
server i all the time got error 403.
The code is the same like in example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class AuthenticationUtil
{
private AuthenticationUtil()
{
}
public static String getToken(String email, String password)
throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(email);
builder.append("&Passwd=").append(password);
builder.append("&accountType=GOOGLE");
builder.append("&source=CloudTut");
builder.append("&service=ac2dm");
// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = con.getOutputStream();
output.write(data);
output.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
String auth_key = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Auth=")) {
auth_key = line.substring(5);
}
}
// Finally get the authentication token
// To something useful with it
return auth_key;
}
}
and the error respond:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.com/accounts/ClientLogin
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at AuthenticationUtil.getToken(AuthenticationUtil.java:48)
at GetAuthenticationToken.main(GetAuthenticationToken.java:8)
This code is from a functioning app and works well for me. It uses the C2DM account login details to request an auth-token, which can then be used to send C2DM messages to client devices. Note that this code is from an Android app, but would typically be executed on the server.
public static String getClientLoginAuthToken() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", "C2DMEMAILADDRESS));
nameValuePairs.add(new BasicNameValuePair("Passwd", "C2DMPASSWORD));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Trace.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
return line.substring(5);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Trace.e(TAG, "Failed to get C2DM auth code");
return "";
}
If you continue to have problems, then best to assume the C2DM account wasn't set up right, and create another one.

Posting data in raw format to PHP file and getting response

I am making an android application where I need to send some data collected from a data to server php file using post data and get the echoed text from the php file and display it. I have the post variables in this format -> "name=xyz&home=xyz" and so on. I am using the following class to post, but the php file on the server does not get the post vars. Can someone please tell me whats wrong or any other ways to do what I am trying to do?
package xxx.xxx.xxx;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetUtil {
public static String UrlToString(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.write(urlParameters.getBytes("UTF-8"));
wr.flush ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
I get a response from php file, but the php file does not get the post data.
The example looks okay to me for a beginner. Only the following springs out:
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
and
wr.write(urlParameters.getBytes("UTF-8"));
In the first you're converting chars to bytes using platform default encoding. The resulting length is not necessarily the same as when using UTF-8 encoding to convert chars to bytes as you did when writing the request body. So the chance exist that the Content-Length header is off from the actual content length. To fix this, you should be using the same charset on the both calls.
But I believe that PHP isn't really that strict when parsing the request body so that you would get nothing in the PHP end. Probably the urlParameters is not in proper format. Are they really URL-encoded?
Anyway, did you try it with Android's builtin HttpClient API? It should be as simple as follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "xyz"));
params.add(new BasicNameValuePair("home", "xyz"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
InputStream input = response.getEntity().getContent();
// ...
If that doesn't work as well, then the mistake is likely in the PHP side.

Categories

Resources