posting XML request in java - java

How do I post an XML request to a URL using HTTP POST and retrieve the response?
Update Sorry, my question was not clear I guess. I want to know how to post an XML request to an URL using either HttpClient or URLConnection and get the response as a POST parameter and display it in a webpage.

Here's an example how to do it with java.net.URLConnection:
String url = "http://example.com";
String charset = "UTF-8";
String param1 = URLEncoder.encode("param1", charset);
String param2 = URLEncoder.encode("param2", charset);
String query = String.format("param1=%s&param2=%s", param1, param2);
URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // Triggers POST.
urlConnection.setRequestProperty("accept-charset", charset);
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset);
writer.write(query); // Write POST query string (if any needed).
} finally {
if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
}
InputStream result = urlConnection.getInputStream();
// Now do your thing with the result.
// Write it into a String and put as request attribute
// or maybe to OutputStream of response as being a Servlet behind `jsp:include`.

This example post an xml file, it depends on Jakarta HttpClient API (jakarta.apache.org)
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* This is a sample application that demonstrates
* how to use the Jakarta HttpClient API.
*
* This application sends an XML document
* to a remote web server using HTTP POST
*
* #author Sean C. Sullivan
* #author Ortwin Glück
* #author Oleg Kalnichevski
*/
public class PostXML {
/**
*
* Usage:
* java PostXML http://mywebserver:80/ c:\foo.xml
*
* #param args command line arguments
* Argument 0 is a URL to a web server
* Argument 1 is a local filename
*
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println(
"Usage: java -classpath <classpath> [-Dorg.apache.commons."+
"logging.simplelog.defaultlog=<loglevel>]" +
" PostXML <url> <filename>]");
System.out.println("<classpath> - must contain the "+
"commons-httpclient.jar and commons-logging.jar");
System.out.println("<loglevel> - one of error, "+
"warn, info, debug, trace");
System.out.println("<url> - the URL to post the file to");
System.out.println("<filename> - file to post to the URL");
System.out.println();
System.exit(1);
}
// Get target URL
String strURL = args[0];
// Get file to be posted
String strXMLFilename = args[1];
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
// Specify content type and encoding
// If content encoding is not explicitly specified
// ISO-8859-1 is assumed
post.setRequestHeader(
"Content-type", "text/xml; charset=ISO-8859-1");
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
} finally {
// Release current connection to the connection pool
// once you are done
post.releaseConnection();
}
}
}

Use InputStreamEntity. I used httpclient 4.2.1.
For example:
HttpPost httppost = new HttpPost(url);
InputStream inputStream=new ByteArrayInputStream(xmlString.getBytes());//init your own inputstream
InputStreamEntity inputStreamEntity=new InputStreamEntity(inputStream,xmlString.getBytes());
httppost.setEntity(inputStreamEntity);

Warning this code is 5+ years old. I did some modfying for this post and never tested it.
Hopefully it helps.
Post XML (data) to a server and downlod the resp:
public int uploadToServer(String data) throws Exception {
OutputStream os;
URL url = new URL("someUrl");
HttpURLConnection httpConn= (HttpURLConnection) url.openConnection();
os = httpConn.getOutputStream();
BufferedWriter osw = new BufferedWriter(new OutputStreamWriter(os));
osw.write(data);
osw.flush();
osw.close();
return httpConn.getResponseCode();
}
public String downloadFromServer() throws MalformedURLException, IOException {
String returnString = null;
StringBuffer sb = null;
BufferedInputStream in;
//set up httpConn code not included same as previous
in = new BufferedInputStream(httpConn.getInputStream());
int x = 0;
sb = new StringBuffer();
while ((x = in.read()) != -1) {
sb.append((char) x);
}
in.close();
in = null;
if (httpConn != null) {
httpConn.disconnect();
}
return sb.toString();
}
Somewhere else.....
int respCode = uploadToServer(someXmlData);
if (respCode == 200) {
String respData = downloadFromServer();
}

Related

How to get response as XML from webService response?

I have to create a method for getting webService response as xml. I know how to create with Java class but problem is getting response as xml from webService.
These webServices are soap based.
Thanks in advance.
I have just solve my problem. HttpURLConnection helps me.
The following code block show how I make poster for getting xml response in java like Mozilla Poster.
public static void main(String[] args) {
try {
String uri = "http://test.com/IntegratedServices/IntegratedServices.asmx?op=GetUserInfo";
String postData = new XmlTest().xmlRequest("QWERTY10");
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // This is important. If you not set doOutput it is default value is false and throws java.net.ProtocolException: cannot write to a URLConnection exception
connection.setRequestMethod("POST"); // This is method type. If you are using GET method you can pass by url. If method post you must write
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // it is important if you post utf-8 characters
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // This three lines is importy for POST method. I wrote preceding comment.
wr.write(postData.getBytes());
wr.close();
InputStream xml = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(xml));
String line = "";
String xmlResponse = "";
while ((line = reader.readLine()) != null) {
xmlResponse += line;
}
File file = new File("D://test.xml"); // If you want to write as file to local.
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(xmlResponse);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String xmlRequest(String pin) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+ " <soap:Body>\n"
+ " <GetUserInfo xmlns=\"http://tempuri.org/\">\n"
+ " <pin>" + pin + "</pin>\n"
+ " </GetUserInfo>\n"
+ " </soap:Body>\n"
+ "</soap:Envelope>";
}
I hope this helps who want to get xml as response. Also I wrote detailed comment to my code.
For soap type webservice :
Parsing SOAP Response in Java
For rest look at this link:
http://duckranger.com/2011/06/jaxb-without-a-schema/

POST params empty, what am I doing wrong? HttpURLConnection / Android / Java

The code below shows a method, downloadUrl(), that takes a String, "myurl," its parameter. There are only two possible urls that I ever send to it, and the behavior of the method is different for each.
when myurl = URL1, it uses a GET request and everything works fine.
when myurl = URL2, however, it uses a POST request, and the response from the php page indicates that the post parameters sent with the request were empty. You can see the line where I set the POST params, so I don't understand why it's sending no params?!
Thanks for any help!
-Adam.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
String response = "";
try {
URL urlObject = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection();
// find out if there's a way to incorporate these timeouts into the progress bar
// and what they mean for shitty network situations
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
// INSERTED QUICK CHECK TO SEE WHICH URL WE ARE LOADING FROM
// it's important because one is GET, and one is POST
if (myurl.equals(url2)){
Log.i(TAG, "dlurl() in async recognizes we are doing pre-call");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String postParams = "?phone=" + phone;
writer.write(postParams);
Log.i(TAG, "we're adding " + postParams + "to " + urlObject);
writer.flush();
writer.close();
os.close();
}
else {
conn.setRequestMethod("GET");
conn.connect();
}
// Starts the query
int responseCode = conn.getResponseCode();
Log.i(TAG, "from " + myurl + ", The response code from SERVER is: " + responseCode);
is = conn.getInputStream();
// Convert the InputStream into a string
// i guess we look up how to do this
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "from downloadUrl, php page response was not OK: " + responseCode;
}
// it's good to close these things?
is.close();
conn.disconnect();
Log.i(TAG, "response is " + response);
return response;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
try with following code block to send parameters of the POST request.
Map<String,String> params = new LinkedHashMap<>();
params.put("phone", "phone");
StringBuilder postPraamString = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postPraamString.length() != 0) postPraamString.append('&');
postPraamString.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postPraamString.append('=');
postPraamString.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
writer.write(postDataBytes);
So I figured out the root of the problem...
In the line:
String postParams = "?phone=" + phone;
The problem was that leading question mark. The question mark should only be used in GET requests.

Not able to execute URL with json value in JAVA API springs

I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE

Getting 411 response code while getting JSON Response

In my application, I am trying get the response using POST request. The response server is sending me in Json format. But after adding the properties, it is returning me the response code as 411 (i.e issue with content length).
I have already added the content length. Then where is the issue i am not getting. Here is my code:
String url = "https://xxx:8243/people/v3";
STRURL = url + HttpComm.getConnectionString().trim();
StringBuffer postData = new StringBuffer();
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
postData.append("?username="+user);
postData.append("&password="+password);
String encodedData = postData.toString();
byte[] postDataByte = postData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type","application/json");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postData.toString().getBytes());
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
{
}
Updated Code :
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
There are a few things that don't look quite right here. I would recommend trying this:
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
What I changed:
As #samlewis said, the code was creating a variable to hold the post data bytes, but then was not using it when it called out.write().
The code set the content type to JSON, but it was not sending JSON. The request was simply two parameters. The response may be JSON, but you don't specify that in the request's Content-Type parameter.
The username/password parameters were encoded just using strings. Normally, it's best to use the URLEncodedPostData class to hold your POST parameters.
If you are going to use strings, I think it was still incorrect to add a ? to the front of the username parameter. If you want to encode parameters in a GET URL, then you use https://xxx:8243/people/v3?username=user&password=password. But, this code was using POST, not GET.
There was also an unused encodedData variable.

how to get data to a servlet which is send using httpcommunicator with post method

I am trying to send data using httpcommunicator class.
here is my code.
public String postData(String address,String dataToBePosted) throws MalformedURLException,IOException,ProtocolException{
/** set up the http connection parameters */
HttpURLConnection urlc = (HttpURLConnection) (new URL(address)).openConnection();
urlc.setRequestMethod("POST");
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = null;
out = urlc.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(dataToBePosted);
writer.close();
out.close();
/** read the response back from the posted data */
BufferedReader bfreader = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
StringBuilder builder = new StringBuilder(100);
String line = "";
while ((line = bfreader.readLine()) != null) {
builder.append(line+"\n");
}
bfreader.close();
/** return the response back from the POST */
return builder.toString();
I am sending it to my servlet.
but i dint know how to retrieve it.
is there any method like getPerameter or else?
Thank you.
I haven't tried your code, but it looks reasonable to me, with the possible exception that you don't appear to be disconnecting your HttpUrlConnection when you've finished with it.
When you run the code, what happens? Do you see an exception? Can you tell that it has reached the servlet? What do you see if you look at the contents of builder by doing System.out.println(builder.toString()?

Categories

Resources