Get the JSON response instead of text/html - java

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());
}

Related

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);
}

Call RestFull Web Service inside Servlet

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.

How can i get any value from json calls (Post, Get, JSON) with Selenium WebDriver on Java?

I have a following functionality: I create through the user form a new user. After i had submitted the entered data, created user get the bar-code, which would be used for get access to the other system section by scanning that bar-code with hand-scanner. So how can i get any value (in my case that bar-code from json calls (Post, Get, JSON) with Selenium WebDriver on Java?
Selenium has nothing to do with json. You can use Apache HttpClient library for sending GET, POST, PUT and DELETE requests and receiving the responses. Given below is a simplified function for all cases.
public static HttpResponse sendRequest(String requestType, String body,String url,
String... headers) throws Exception {
try {
HttpGet getRequest = null;
HttpPost postRequest;
HttpPut putRequest;
HttpDelete delRequest;
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
// Collecting Headers
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String arg : headers) {
//Considering that you are applying header name and values in String format like this "Header1,Value1"
nvps.add(new BasicNameValuePair(arg.split(",")[0], arg
.split(",")[1]));
}
System.out.println("Total Headers Supplied " + nvps.size());
if (requestType.equalsIgnoreCase("GET")) {
getRequest = new HttpGet(url);
for (NameValuePair h : nvps) {
getRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(getRequest);
}
if (requestType.equalsIgnoreCase("POST")) {
postRequest = new HttpPost(url);
for (NameValuePair h : nvps) {
postRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
postRequest.setEntity(requestEntity);
response = client.execute(postRequest);
}
if (requestType.equalsIgnoreCase("PUT")) {
putRequest = new HttpPut(url);
for (NameValuePair h : nvps) {
putRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
putRequest.setEntity(requestEntity);
response = client.execute(putRequest);
}
if (requestType.equalsIgnoreCase("DELETE")) {
delRequest = new HttpDelete(url);
for (NameValuePair h : nvps) {
delRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(delRequest);
}
return response;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Selenium only deals with browsers.
Java has classes that do http requests.
see the code below:
private HttpURLConnection setODataConnection(String url, String method) {
try {
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod(method);
// add request header
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json;odata=verbose");
return conn;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private StringBuilder sendODataRequest(HttpURLConnection conn) {
try {
int responseCode = conn.getResponseCode();
String method = conn.getRequestMethod();
System.out.println("\nSending '" + method + "' request to URL : " + conn.getURL());
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private ArrayList<String> getByFullUrl(String fullUrl, String entity) {
HttpURLConnection conn = setODataConnection(fullUrl, "GET");
StringBuilder response = sendODataRequest(conn);
ArrayList<String> s = new ArrayList<String>();
Pattern p = Pattern.compile(entity + "\" : (.*?)\\}");
Matcher m = p.matcher(response);
while (m.find()) {
s.add(m.group(1).replace("\"", ""));
}
return s;
}
public ArrayList<String> get(String table, String entity) {
String url = oDataUrl + table + "?$select=" + entity;
return getByFullUrl(url, entity);
}
public void post(String table, String bodyDetails) {
String url = oDataUrl + table;
HttpURLConnection conn = setODataConnection(url, "POST");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}
public void put(String table, String id, String bodyDetails) {
String url = oDataUrl + table + "(" + id + ")";
HttpURLConnection conn = setODataConnection(url, "PUT");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}

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 send json data to POST restful service

I want to call a rest webservice with POST method.Below is the service url and its parameters which I need to pass
Rest Service: https://url/SSOServer/SSO.svc/RestService/Login
Json Object {"ProductCode":"AB","DeviceType":"android Simulator","UserName":"","ModuleCode":"AB_MOBILE","DeviceId":"device-id","Version":"1.0.0.19","CustomerCode":"w","Password":""}
Here is my post request code:
public void sendHttpPost() throws ClientProtocolException, IOException{
HttpPost httpPostRequest = new HttpPost(url + buildParams());
// add headers
Iterator it = headers.entrySet().iterator();
Iterator itP = params.entrySet().iterator();
while (it.hasNext()) {
Entry header = (Entry) it.next();
httpPostRequest.addHeader((String)header.getKey(), (String)header.getValue());
}
HttpClient client = new DefaultHttpClient();
HttpResponse resp;
resp = client.execute(httpPostRequest);
this.respCode = resp.getStatusLine().getStatusCode();
Log.i(TAG, "response code: " + getResponseCode());
this.responsePhrase = resp.getStatusLine().getReasonPhrase();
Log.i(TAG, "error msg: " + getErrorMsg());
HttpEntity entity = resp.getEntity();
if (entity != null){
InputStream is = entity.getContent();
//Header contentEncoding = resp.getFirstHeader("Content-encoding");
//Log.i(TAG, "endoding" + contentEncoding.getValue());
response = convertStreamToString(is);
//response = response.substring(1,response.length()-1);
//response = "{" + response + "}";
Log.i(TAG, "response: " + response);
is.close();
}
}
My question is how to add json data to this request??
Use below class
public class RestClient
{
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse()
{
return response;
}
public String getErrorMessage()
{
return message;
}
public int getResponseCode()
{
return responseCode;
}
public RestClient(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch (method)
{
case GET:
{
// add parameters
String combinedParams = "";
if (!params.isEmpty())
{
combinedParams += "";
for (NameValuePair p : params)
{
String paramString = p.getName() + "" + URLEncoder.encode(p.getValue(),"UTF-8");
if (combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
// add headers
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
// add headers
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty())
{
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url) throws Exception
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
}
private static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
public InputStream getInputStream(){
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try
{
HttpPost request = new HttpPost(url);
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
return instream;
/* response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();*/
}
}
catch (ClientProtocolException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
catch (IOException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return null;
}
public enum RequestMethod
{
GET,
POST
}
}
Here is the code how to use above class
RestClient client=new RestClient(Webservices.student_details);
JSONObject obj=new JSONObject();
obj.put("StudentId",preferences.getStudentId());
client.AddParam("",obj.toString());
client.Execute(RequestMethod.GET);
String response=client.getResponse();
Hope this will help you
Q: how to add json data to this request?
A: Set your content type, length and write the payload.
Here's an example:
http://localtone.blogspot.com/2009/07/post-json-using-android-and-httpclient.html
JSONObject holder = new JSONObject();
...
JSONObject data = new JSONObject();
...
// Some example name=value pairs
while(iter.hasNext()) {
Map.Entry pairs = (Map.Entry)iter.next();
String key = (String)pairs.getKey();
Map m = (Map)pairs.getValue();
JSONObject data = new JSONObject();
Iterator iter2 = m.entrySet().iterator();
while(iter2.hasNext()) {
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
holder.put(key, data);
}
...
StringEntity se = new StringEntity(holder.toString());
...
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
...

Categories

Resources