Call RestFull Web Service inside Servlet - java

i have a standard HttpServlet in my java web project. I use Netbeans. I want to call a Restfull Web service inside servlet and after i will catch the response like a JSON and populate a JSP.
I tried to find on the net but i didn't find anything.
Thank you

Here's an example of HttpPost:
try {
HttpPost httpPost = new HttpPost("https://exampleurl/providerexample/api/v1/loansforexample"
);
StringEntity params;
params = new StringEntity("{"
+ "\"clientId\": \"" + "2" + "\","
+ "\"productId\": \"" + "1" + "\","
+ "\"locale\": \"" + "en" + "\"}");
httpPost.addHeader("Content-Type", "text/html"); //or text/plain
httpPost.addHeader("Accept-Encoding", "gzip, deflate, sdch");
httpPost.setEntity(params);
HttpResponse response = client.execute(httpPost);
int statuscode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
if (statuscode == 200) {
System.out.println(responseBody);
}
if (statuscode != 200) {
System.out.println(responseBody);
// JSONObject obj = new JSONObject(responseBody);
// JSONArray errors = obj.getJSONArray("errors");
// String errorMessage = "";
// if (errors.length() > 0) {
// errorMessage = errors.getJSONObject(0).getString("developerMessage");
}
}
catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
HttpGet is pretty much the same.

Related

Get the JSON response instead of text/html

authenticate_user method intended to create it to get the list of projects through the REST API in java:
#GET
#Path("/projects")
#Produces({MediaType.APPLICATION_JSON})
public boolean authenticate_user(String username, String password)
{
boolean status = false;
boolean isUser = isUserExists(username, password);
if (isUser)
{
HttpResponse response = clientConfig(username, password, "projects");
System.out.println("ProjectResponse >>>" + response);
HttpEntity entity = response.getEntity();
String content=null;
try
{
content = EntityUtils.toString(entity);
}
catch (ParseException | IOException e)
{
e.printStackTrace();
}
System.out.println("ResponseContent><><><"+content);
System.out.println("ContentMimeType: "+EntityUtils.getContentMimeType(entity));
if (response != null)
{
JSONArray getArray =new JSONArray();//Projects
status=true;
System.out.println("SuccessFully login");
}else
{
// TODO user is not validated
System.out.println("Error: Not Authenticated");
status = false;
}
} return status;
}
ClientConfiguration class:
public HttpResponse clientConfig(String username, String password, String prms)
{
try
{
HttpClient httpclient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://" + _HOST + "/" + prms);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("Type", "Basic Auth"));
nvps.add(new BasicNameValuePair("Username", username));
nvps.add(new BasicNameValuePair("Password", password));
httpget.setHeader("Authorization", "Basic " + new UrlEncodedFormEntity(nvps));
// Execute and get the response.
httpget.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpget, httpContext);
response.setHeader("Content-Type", "application/json");
if (response.getStatusLine().getStatusCode() != 200)
{
throw new IOException("Non-successful HTTP response: " + response.getStatusLine().getStatusCode() + ":"
+ response.getStatusLine().getReasonPhrase());
}
else if (response.getStatusLine().getStatusCode() == 200)
{
System.out.println("Response>>>" + response);
System.out.println("HTTPResponse: " + response.getStatusLine().getStatusCode() + ":"
+ response.getStatusLine().getReasonPhrase());
flag = true;
return response;
}
else
{
System.out.println("Status is not 200");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
And my output is html response instead of html response I need the JSON format, Its return me login page
HTTPResponse: 200:OK
<!DOCTYPE html>
<html lang="en">
................ </html>
ContentMimeType: text/html
SuccessFully login
Any one help me to find out the problem.
Try like this:
String json_string = EntityUtils.toString(response.getEntity());
JSONArray jsonArr = new JSONArray(json_string);
Thank you, Friends, Now I solved this issue with Jersey framework. And here is a solution of it.
String url = "http://support.sigmastream.com/issues.json";
String output = "";
String authString = username + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
try
{
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc).get(ClientResponse.class);
if (resp.getStatus() != 200)
{
throw new IOException(
"Non-successful HTTP response: " + resp.getStatus() + " : " + resp.getStatusInfo());
}
else
{
output = resp.getEntity(String.class);
System.out.println("response: " + output);
}
}
catch (IOException ie)
{
System.out.println(ie.getMessage());
}

How to get response from HttpPost

I want to get response from the httppost request. I get the network response like 200,405,404 but i don't get the value which is coming from server. I am trying a lot but i don't get response. Please help...
My code is below-
private void UploadPost() {
SharedPreferences sharedPreferences1 = getSharedPreferences("DATA", Context.MODE_PRIVATE);
String ID = sharedPreferences1.getString("id", "");
#SuppressWarnings("deprecation")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url.addOffer_url);
Log.e("uploadFile", "Source File Path " + picturePath);
File sourceFile1 = new File(picturePath);
if (!sourceFile1.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
imgUploadStatus = "Source File Does not exist";
}
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity();
File sourceFile = new File(picturePath);
MultipartEntity entity1 = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// Adding file data to http body
entity.addPart("retailer_id", new StringBody(ID));
entity.addPart("title", new StringBody(addoffertitle));
entity.addPart("description", new StringBody(addofferdesc));
entity.addPart("keyword", new StringBody(addofferkeyword));
entity.addPart("offer_id", new StringBody(OfferListing_Id));
// entity.addPart("payment_status",new StringBody(paymentStatus));
// if(!picturePath.equals(""))
entity.addPart("offer_image", new FileBody(sourceFile));
/* else
entity.addPart("old_pic",new StringBody(Image_Path));*/
httppost.setEntity(entity);
Log.d("httppost success", "httppost");
//Run a api for net conn check
try {
String responseString= new String();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity8 = response.getEntity();
if(entity8 !=null){
responseString = EntityUtils.toString(entity8, "UTF-8");
System.out.println("Response body: " + responseString);
}
statusCode = 200;
} catch (FileNotFoundException e) {
Log.e("log_tag1", "Error FileNotFoundException new service" + e.toString());
result = "FileNotFoundException";
} catch (SocketTimeoutException e) {
Log.e("log_tag2", "SocketTimeoutException new service " + e.toString());
result = "SocketTimeoutException";
} catch (Exception e) {
Log.e("log_tag3", "Error converting OtherException new service " + e.toString());
result = "OtherException";
}
if (statusCode == 200) {
// Server response
responseString = "success";
Log.e("complete success", "Response from server: " + responseString);
} else if (statusCode == 404) {
responseString = "page not found";
Log.e("complete page not found", "Response from server: " + responseString);
} else if (statusCode == 405) {
responseString = "no net";
Log.e("complete no net", "Response from server: " + responseString);
} else {
responseString = "other";
Log.e("complete other", "Response from server: " + responseString);
}
} catch (Exception e) {
responseString = e.toString();
responseString = "other";
Log.e("complete", "Response from server: " + responseString);
}
}
I want to response from the httppost.i get the network response but i don't get the value which is coming from server.I am trying a lot but i don't get response.Please help...
Try using EntityUtils instead of the BufferedReader. For instance, something like:
String responseString= new String();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity !=null){
responseString = EntityUtils.toString(entity, "UTF-8");
}
Look at the selected answer here - it shows how to get response body for a 400-HTTP response. You can also look at this example. If you are working with JSON payload, perhaps you might want to consider using Volley - here are some examples for PUT, POST, and GET requests using Volley
You can try this
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
Instead of
HttpEntity entity8 = response.getEntity();
if(entity8 !=null){
responseString = EntityUtils.toString(entity8, "UTF-8");
System.out.println("Response body: " + responseString);
}

Javax-RS - how to create a client to push data to a server?

I need to push data from a standalone client back to the server. This client already accesses the server to get information, parses it, executes what it has to do, but now I need it to push back some information.
I have tried doing this:
public class UpdateServer {
public void update(int resultSetRowCount) {
AgentConfiguration config = new AgentConfiguration();
config.init();
String agentId = AgentConfiguration.agent_id;
String serverIp = AgentConfiguration.server_ip;
String serverPort = AgentConfiguration.server_port;
Calendar cal = Calendar.getInstance();
StringBuilder timestamp = new StringBuilder();
timestamp.append(cal.get(Calendar.YEAR));
timestamp.append(String.format("%02d",cal.get(Calendar.MONTH) + 1));
timestamp.append(String.format("%02d",cal.get(Calendar.DAY_OF_MONTH)));
timestamp.append(String.format("%02d",cal.get(Calendar.HOUR_OF_DAY)));
timestamp.append(String.format("%02d",cal.get(Calendar.MINUTE)));
timestamp.append(String.format("%02d",cal.get(Calendar.SECOND)));
String date = timestamp.toString();
String uri = "http://" + serverIp + ":" + serverPort + "/hrm/alerts/" + agentId + "/" + date + "/" + resultSetRowCount;
System.out.println(uri);
try {
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
// Create new patchRequest with below mentioned URL
HttpPost postRequest = new HttpPost(uri);
// Add additional header to postRequest which accepts application/xml data
postRequest.addHeader("accept", "application/xml");
// Execute your request and catch response
HttpResponse response = httpClient.execute(postRequest);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm trying to access the server with the formatted uri using:
new UpdateServer().update(resultSetRowCount);
But I'm getting the following exception:
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 405
What am I missing here?
One of the causes of http error code 405 is when a payload is not passed to the POST method. Probably that is the case with your program.
You can use PostMethod instead of HttpPost and set the payload
Your code will look like
...
String uri = "http://" + serverIp + ":" + serverPort + "/hrm/alerts/" + agentId + "/" + date + "/" + resultSetRowCount;
System.out.println(uri);
try
{
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
PostMethod post = new PostMethod(uri);
RequestEntity requestEntity = new StringRequestEntity(payload, "application/xml", null/*charset default*/);
post.setRequestEntity(requestEntity);
int iResult = httpclient.executeMethod(post);
// get the status code using post.getStatusCode()
// you can get the response using post.getResponseBodyAsString()
// Check for HTTP response code: 200 = success
if (post.getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + post.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

HttpClientFormSubmit to get the OAUTH access token

I am using httpcomponents-client-4.2.5-bin for the ClientFormSubmit. I used the example to login to facebook using Oauth. My Oauth login has following steps
first login to facebook using
https://www.facebook.com/dialog/oauth?client_id=xxxxxxx&redirect_uri=http://localhost:8080/
give the login details it redirects to the local host and have code parameter in url
I need to get that code value.
Code is
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://www.facebook.com/dialog/oauth?client_id=358300034293206&redirect_uri=http://localhost:8080/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://www.facebook.com/dialog/oauth?client_id=358300034293206&redirect_uri=http://localhost:8080/");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "*****"));
nvps.add(new BasicNameValuePair("pass", "*****"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Double check we've got right page " + EntityUtils.toString(entity));
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
httpclient.getConnectionManager().shutdown();
}catch(Exception e)
{
System.out.println( "Something bad just happened." );
System.out.println( e );
e.printStackTrace();
}
}
Is it possible to get the redirect url using request header? Thanks In Advance.
Using HttpClient 4.3 APIs
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
HttpGet httpGet = new HttpGet("http://www.google.com/");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet, context);
try {
System.out.println("Response status: " + httpResponse.getStatusLine());
System.out.println("Last request URI: " + context.getRequest().getRequestLine());
URICollection redirectLocations = context.getRedirectLocations();
if (redirectLocations != null) {
System.out.println("All intermediate redirects: " + redirectLocations.getAll());
}
EntityUtils.consume(httpResponse.getEntity());
} finally {
httpResponse.close();
}
Using HttpClient 4.2 APIs
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext context = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.google.com/");
try {
HttpResponse httpResponse = httpClient.execute(httpGet, context);
System.out.println("Response status: " + httpResponse.getStatusLine());
HttpRequest req = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
System.out.println("Last request URI: " + req.getRequestLine());
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
DefaultRedirectStrategy.REDIRECT_LOCATIONS);
if (redirectLocations != null) {
System.out.println("All intermediate redirects: " + redirectLocations.getAll());
}
EntityUtils.consume(httpResponse.getEntity());
} finally {
httpGet.releaseConnection();
}

How to build a http post request with the correct entity with Java and not using any library?

How should I build the entity to achieve this post request?
POST https://picasaweb.google.com/data/feed/api/user/userID/albumid/albumID/photoid/photoID
<entry xmlns='http://www.w3.org/2005/Atom'>
<content>great photo!</content>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/photos/2007#comment"/>
</entry>
It's from:
http://code.google.com/intl/zh-TW/apis/picasaweb/docs/2.0/developers_guide_protocol.html#AddComments
Could someone provide an example or any tips?
Many thanks.
UPDATE:
I added my code here:
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("GData-Version", "2"));
headers.add(new BasicHeader("Authorization", "GoogleLogin auth=" + mAuthToken));
EntityTemplate entity = new EntityTemplate(new ContentProducer() {
public void writeTo(OutputStream ostream) throws IOException {
Writer writer = new OutputStreamWriter(ostream, "UTF-8");
writer.write("\r\n");
writer.write("<entry xmlns='http://www.w3.org/2005/Atom'>");
writer.write("<content>" + comment + "</content>");
writer.write("<category scheme=\"http://schemas.google.com/g/2005#kind\"\r\n");
writer.write("term=\"http://schemas.google.com/photos/2007#comment\"/>");
writer.write("</entry>\r\n");
writer.flush();
}
});
Still no luck. Any idea?
It is a sample code using HttpClient.
I hope this piece of information will be of help to you.
// yourID
String userID = "";
String albumID = "";
String photoID = "";
HttpPost postRequest = new HttpPost(
"https://picasaweb.google.com/data/feed/api/user/" + userID
+ "/albumid/" + albumID + "/photoid/" + photoID);
postRequest.addHeader(new BasicHeader("GData-Version", "2.0"));
postRequest.addHeader(new BasicHeader("Authorization",
"GoogleLogin auth=" + mAuthToken));
String content =
"<entry xmlns='http://www.w3.org/2005/Atom'>"
+ "<content>" + comment + "</content>"
+ "<category scheme='http://schemas.google.com/g/2005#kind'"
+ " term='http://schemas.google.com/photos/2007#comment'/>"
+ "</entry>";
try {
StringEntity entity = new StringEntity(content);
entity.setContentType(new BasicHeader("Content-Type",
"application/atom+xml"));
postRequest.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(postRequest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use "GDataAPI" and "Guava-libraries".
PicasawebService myService
= new PicasawebService("exampleCo-exampleApp-1"); // just id
myService.setUserCredentials(
"liz#gmail.com", "mypassword"); // your mailaddress, password
// change "username", "albumid" and "photoid"
URL feedUrl = new URL(
"https://picasaweb.google.com/data/feed/api/"
+ "user/username/albumid/albumid/photoid/photoid");
CommentEntry myComment = new CommentEntry();
myComment.setContent(
new PlainTextConstruct("great photo!")); // there is comment
myService.insert(feedUrl, myComment);
Refere to following URL.
http://code.google.com/intl/ja/apis/picasaweb/docs/2.0/developers_guide_java.html
http://code.google.com/p/gdata-java-client/downloads (GDataAPI Download)
http://code.google.com/p/guava-libraries/ (Guava-libraries)
You can use HttpClient from apache httpcomponents to create http requests.
Find the tutorials here.

Categories

Resources