Java: How to send a XML request? - java

i need to send a xml request in java and catch the response.
How can i do this ?
I search in the google but nothing solid until now.
Best regards,
Valter Henrique.

If you are looking to do an HTTP POST, then you could use the java.net.* APIs in Java SE:
try {
URL url = new URL(URI);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
// Write your XML to the OutputStream (JAXB is used in this example)
jaxbContext.createMarshaller().marshal(customer, os);
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}

XML is a data format. If you talk about requests/responses, you need to know the protocol.
My guess is that the protocol you are using is HTTP(S) and you have to do a POST with your XML request, but this is just an educated(?) guess.

You can use playframework. It is the easiest web framework I have ever used in Java. It is resembles to rails but in java. Give it a try.
http://www.playframework.org/
It has a nice and easy to use template engine based on groovy. You can set a request format as described here.
http://www.playframework.org/documentation/1.1/routes
Go for documentation for details. You will implement your first website that can send and get requests in just hours.

Related

Rest api call and POST request (java)

I am pretty new concerning REST api and POST request.
I have the url of a REST api. I need to access to this api by doing an API call in JAVA thanks to a client id and a client secret (I found a way to hash the client secret). However, as I am new I don't know how to do that api call. I did my research during this all day on internet but I found no tutorial, website or anything else about how to do an api call. So please, does anyone know a tutorial or how to do that? (if you also have something about POST request it would be great)
I would be very thankful.
Thank you very much for your kind attention.
Sassir
Here's a basic example snippet using JDK classes only. This might help you understand HTTP-based RESTful services a little better than using a client helper. The order in which you call these methods is crucial. If you have issues, add a comments with your issue and I will help you through it.
URL target = new URL("http://www.google.com");
HttpURLConnectionconn = (HttpURLConnection) target.openConnection();
conn.setRequestMethod("GET");
// used for POST and PUT, usually
// conn.setDoOutput(true);
// OutputStream toWriteTo = conn.getOutputStream();
conn.connect();
int responseCode = conn.getResponseCode();
try
{
InputStream response = conn.getInputStream();
}
catch (IOException e)
{
InputStream error = conn.getErrorStream();
}
You can also use RestTemplate from Spring: https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate
Fast and simple solution without any boilerplate code.
Simple example:
RestTemplate rest = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("firstParamater", "parameterValue");
map.add("secondParameter", "differentValue");
rest.postForObject("http://your-rest-api-url", map, String.class);
The Restlet framework also allows you to do such thing thanks to its class ClientResource. In the code below, you build and send a JSON content within the POST request:
ClientResource cr = new ClientResource("http://...");
SONObject jo = new JSONObject();
jo.add("entryOne", "...");
jo.add("entryTow", "...");
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Restlet allows to send any kind of content (JSON, XML, YAML, ...) and can also manage the bean / representation conversion for you using its converter feature (creation of the representation based on a bean - this answer gives you more details: XML & JSON web api : automatic mapping from POJOs?).
You can also note that HTTP provides an header Authorization that allows to provide authentication hints for a request. Several technologies are supported here: basic, oauth, ... This link could help you at this level: https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/.
Using authentication (basic authentication for example) can be done like this:
String username = (...)
String password = (...)
cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, username, password);
(...)
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Hope it helps you,
Thierry

Trouble sending a POST with Java

I've read through the other excellent stack overflow articles and tried a lot of them and variations on them but must be making some basic error time and time again? The page I'm posting to works but when I run my java program I just get an empty set on the mySQL database that the data is being posted to. The direct URL that works would be:
http://myURL.co.uk/enteremail.php?email=value
the code
String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
URL url = new URL("http://myURL.co.uk/enteremail.php");
URLConnection conn = url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
I know that there are much better ways of doing this using java but I have to use this way as its a bit of a workaround for another problem.
TIA
You need to close the URL connection as well.
I'd suggest checking out the Apache Http client which will do all the heavy lifting for you.
I'd still like to know what was up with my original code, but because what I wanted to do was so simple I've just cut a corner and done this which works for sending the post request to a php page but may not be the solution for anything else:
String email = "myEmail";
URL post= new URL("http://myURL.co.uk/enteremail.php?email="+email);
URLConnection goPost = post.openConnection();
new InputStreamReader(goPost.getInputStream());
Hopefully of some help to someone else down the line, KISS

Better way to send lots of text to a server?

I have a java application that sends text to a sql database on a server. Currently my java application takes the text, puts it into the url, then sends it to a php page on the server that takes it with GET and puts it in the database. that works fine to an extent, the problem is, that i need to be able to send lots of text, and i keep getting 414, uri to long errors. is there a better way to do this?
ok, i tried what you said, and read the tutorial, but something is not working. here is my code that i tried
public void submitText(String urls,String data) throws IOException{
URL url = new URL(urls);
URLConnection con = url.openConnection();
con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
out.write(data);
out.flush();
}
submitText(server + "publicPB.php", "param=" + text);
here is my php code
$param = $_POST['param'];
$sql = "UPDATE table SET cell='{$param}' WHERE 1";
mysql_query($sql);
...
im pretty sure its not a problem with the php as the php worked fine with GET, and thats all i change with it, my problem i think is that im not 100% sure how to send data to it with the java
Use a POST instead of a GET and send the text as the request body. You can only pass so much data to a URL. E.g.:
// Assuming 'input' is a String and contains your text
URL url = new URL("http://hostname/path");
URLConnection con = url.openConnection();
con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
out.write(input);
out.close();
See Reading from and Writing to a URLConnection for more details.
Why don't you use POST to send data across to PHP page? GET does have a smaller limit of content.
Use POST requests, which do not have content length limits.
POST requests do not have length content limits and are much secure than GET requests ;)
If using SQL Server I would look into leveraging BCP. You can write the file and call BCP from within Java, and it will send the information directly to your database.

Java Post File to PHP

How can I post a file to a php using java (as a html form would do) ?
If you simply need to generate an HTTP Post, check out HttpClient, and in particular the PostMethod. Since you're talking HTTP the implementing technology on the server (in your case, PHP) is immaterial.
There's an example here.
It is in fact possible to do a POST using only the classes that are in the JDK, but as others have pointed out it will probably be easier to use a library like HttpClient.
In addition to HttpClient you may also want to look at the client-side java libraries supplied by RESTful frameworks such as Restlet and Jersey. While primarily designed for interacting with web services they offer a very high-level abstraction for GETing and POSTing to just about anything.
Code NOT tested or even compiled (probably doesn't compile), but this is kinda sorta would you'd do if you wanted to roll your own:
URL url = new URL("http://hostname/foo.php");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
// ignoring possible encoding issues
byte[] body = "param=value&param2=value2".getBytes();
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded" );
connection.setRequestProperty("Content-length", String.valueOf(body.length) );
// ignoring possible IOExceptions
OutputStream out = connection.getOutputStream();
out.write(body);
out.flush();
// use this to read back from server
InputStream in = connection.getInputStream();
As you can see, it's pretty low-level stuff. Which is why you want to use a library.
The httpclient library contains all the tools you need to talk to a web server.

Writing post data from one java servlet to another

I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST.
(Non essential xml generating code replaced with "Hello there")
StringBuilder sb= new StringBuilder();
sb.append("Hello there");
URL url = new URL("theservlet's URL");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "" + sb.length());
OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
This is causing a server error, and the second servlet is never invoked.
This kind of thing is much easier using a library like HttpClient. There's even a post XML code example:
PostMethod post = new PostMethod(url);
RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
I recommend using Apache HTTPClient instead, because it's a nicer API.
But to solve this current problem: try calling connection.setDoOutput(true); after you open the connection.
StringBuilder sb= new StringBuilder();
sb.append("Hello there");
URL url = new URL("theservlet's URL");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", "" + sb.length());
OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
outputWriter.write(sb.toString());
outputWriter.flush();
outputWriter.close();
The contents of an HTTP post upload stream and the mechanics of it don't seem to be what you are expecting them to be. You cannot just write a file as the post content, because POST has very specific RFC standards on how the data included in a POST request is supposed to be sent. It is not just the formatted of the content itself, but it is also the mechanic of how it is "written" to the outputstream. Alot of the time POST is now written in chunks. If you look at the source code of Apache's HTTPClient you will see how it writes the chunks.
There are quirks with the content length as result, because the content length is increased by a small number identifying the chunk and a random small sequence of characters that delimits each chunk as it is written over the stream. Look at some of the other methods described in newer Java versions of the HTTPURLConnection.
http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode(int)
If you don't know what you are doing and don't want to learn it, dealing with adding a dependency like Apache HTTPClient really does end up being much easier because it abstracts all the complexity and just works.
Don't forget to use:
connection.setDoOutput( true)
if you intend on sending output.

Categories