The rest service gets proper value when invoked from SOAP UI. But when called from HttpClient get null values.
Rest Service:
@Path("/example")
public class TestService {
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
public Response postXML(@QueryParam("target") String target,@QueryParam("body") String body) {
System.out.println("Target: " + target);
System.out.println("Message: " + body);
return Response.ok("Sucess").build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response postJSON(@QueryParam("target") String target,@QueryParam("body") String body) {
System.out.println("Target: " + target);
System.out.println("Message: " + body);
return Response.ok("Sucess").build();
}
java Http Client:
public void sendXML() throws Exception {
String USER_AGENT = "Mozilla/5.0";
String url = "http://localhost:9080/TestServiceApp/jaxrs/example";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("topic", "topic"));
urlParameters.add(new BasicNameValuePair("body", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><FILE>AgreementDetails.pdf</FILE>"));
HttpEntity reqEntity = new UrlEncodedFormEntity(urlParameters);
System.out.println("Req: " + EntityUtils.toString(reqEntity));
post.setEntity(reqEntity);
post.addHeader("content-type", "application/xml");
HttpResponse response = client.execute(post);
System.out.println("response: " +EntityUtils.toString(response.getEntity()));
}
public void sendJSON() throws Exception {
String USER_AGENT = "Mozilla/5.0";
String url = "http://localhost:9080/TestServiceApp/jaxrs/example";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("topic", "topic"));
urlParameters.add(new BasicNameValuePair("body", "{\"glossary\": {\"title\": \"example glossary\"}}"));
HttpEntity reqEntity = new UrlEncodedFormEntity(urlParameters);
System.out.println("Req: " + EntityUtils.toString(reqEntity));
post.setEntity(reqEntity);
post.addHeader("content-type", "application/json");
HttpResponse response = client.execute(post);
System.out.println("response: " +EntityUtils.toString(response.getEntity()));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
TranslationClient clnt = new TranslationClient();
clnt.sendXML();
clnt.sendJSON();
} catch(Exception e) {
String error = e.getMessage();
if(error == null || error.isEmpty())
e.printStackTrace();
else
System.out.println("Error: " + e.getMessage());
}
}
I tried using StringEntity and MultipartEntityBuilder. With same result.
Thanks Madhu