I have written a REST web service in Netbean IDE using Jersey Framework and Java.
For every request the user needs to provide a username and a password, I know that this authentication is not a best practice (using a curl command like: curl -u username:password -X PUT http://localhsot:8080/user).
Now I want to call a REST web service from an Android Class.
How should I do it?
I have an Android Class which uses DefaultHttpClient and CredentialUsernameAndPassword, but when I run it in Eclipse, sometimes I get a runtime exception or SDK exception.
This is an sample restclient class
public class RestClient
{
public enum RequestMethod
{
GET,
POST
}
public int responseCode=0;
public String message;
public String response;
public void Execute(RequestMethod method,String url,ArrayList<NameValuePair> headers,ArrayList<NameValuePair> params) throws Exception
{
switch (method)
{
case GET:
{
// add parameters
String combinedParams = "";
if (params!=null)
{
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
if (headers!=null)
{
headers=addCommonHeaderField(headers);
for (NameValuePair h : headers)
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
// add headers
if (headers!=null)
{
headers=addCommonHeaderField(headers);
for (NameValuePair h : headers)
request.addHeader(h.getName(), h.getValue());
}
if (params!=null)
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
executeRequest(request, url);
break;
}
}
}
private ArrayList<NameValuePair> addCommonHeaderField(ArrayList<NameValuePair> _header)
{
_header.add(new BasicNameValuePair("Content-Type","application/x-www-form-urlencoded"));
return _header;
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try
{
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);
instream.close();
}
}
catch (Exception e)
{ }
}
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");
}
is.close();
}
catch (IOException e)
{ }
return sb.toString();
}
}
Recently discovered that a third party library - Square Retrofit can do the job very well.
Defining REST endpoint
public interface GitHubService {
#GET("/users/{user}/repos")
List<Repo> listRepos(#Path("user") String user,Callback<List<User>> cb);
}
Getting the concrete service
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();
GitHubService service = restAdapter.create(GitHubService.class);
Calling the REST endpoint
List<Repo> repos = service.listRepos("octocat",new Callback<List<User>>() {
#Override
public void failure(final RetrofitError error) {
android.util.Log.i("example", "Error, body: " + error.getBody().toString());
}
#Override
public void success(List<User> users, Response response) {
// Do something with the List of Users object returned
// you may populate your adapter here
}
});
The library handles the json serialization and deserailization for you. You may customize the serialization and deserialization too.
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new DateTypeAdapter())
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setConverter(new GsonConverter(gson))
.build();
Stop with whatever you were doing ! :)
Implement the RESTful client as a SERVICE and delegate the intensive network stuff to activity independent component: a SERVICE.
Watch this insightful video
http://www.youtube.com/watch?v=xHXn3Kg2IQE where Virgil Dobjanschi is explaining his approach(es) to this challenge...
Using Spring for Android with RestTemplate
https://spring.io/guides/gs/consuming-rest-android/
// The connection URL
String url = "https://ajax.googleapis.com/ajax/" +
"services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");
I used OkHttpClient to call restful web service. It's very simple.
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = httpClient.newCall(request).execute();
String body = response.body().string()
What back-end? If JAVA then you can use REST with Java (JAX-RS) using Jersey.
On the Android side you can use this simple RestClient to work with that REST service.
For JSON <--> Object mapping on both sides (Android, Java back-end) you can use GSON.
Perhaps am late or maybe you've already used it before but there is another one called ksoap and its pretty amazing.. It also includes timeouts and can parse any SOAP based webservice efficiently. I also made a few changes to suit my parsing.. Look it up
Follow the below steps to consume RestFul in android.
Step1
Create a android blank project.
Step2
Need internet access permission. write the below code in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
Step3
Need RestFul url which is running in another server or same machine.
Step4
Make a RestFul Client which will extends AsyncTask. See RestFulPost.java.
Step5
Make DTO class for RestFull Request and Response.
RestFulPost.java
package javaant.com.consuming_restful.restclient;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.util.Map;
import javaant.com.consuming_restful.util.Util;
/**
* Created by Nirmal Dhara on 29-10-2015.
*/
public class RestFulPost extends AsyncTask<map, void,="" string=""> {
RestFulResult restFulResult = null;
ProgressDialog Asycdialog;
String msg;
String task;
public RestFulPost(RestFulResult restFulResult, Context context, String msg,String task) {
this.restFulResult = restFulResult;
this.task=task;
this.msg = msg;
Asycdialog = new ProgressDialog(context);
}
#Override
protected String doInBackground(Map... params) {
String responseStr = null;
Object dataMap = null;
HttpPost httpost = new HttpPost(params[0].get("url").toString());
try {
dataMap = (Object) params[0].get("data");
Gson gson = new Gson();
Log.d("data map", "data map------" + gson.toJson(dataMap));
httpost.setEntity(new StringEntity(gson.toJson(dataMap)));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
DefaultHttpClient httpclient= Util.getClient();
HttpResponse response = httpclient.execute(httpost);
int statusCode = response.getStatusLine().getStatusCode();
Log.d("resonse code", "----------------" + statusCode);
if (statusCode == 200)
responseStr = EntityUtils.toString(response.getEntity());
if (statusCode == 404) {
responseStr = "{\n" +
"\"status\":\"fail\",\n" +
" \"data\":{\n" +
"\"ValidUser\":\"Service not available\",\n" +
"\"code\":\"404\"\n" +
"}\n" +
"}";
}
} catch (Exception e) {
e.printStackTrace();
}
return responseStr;
}
#Override
protected void onPreExecute() {
Asycdialog.setMessage(msg);
//show dialog
Asycdialog.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
Asycdialog.dismiss();
restFulResult.onResfulResponse(s,task);
}
}
For more details and complete code please visit http://javaant.com/consume-a-restful-webservice-in-android/#.VwzbipN96Hs
Here is my Library That I have created for simple Webservice Calling,
You can use this by adding a one line gradle dependency -
compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'
Here is the demonstration of using.
https://github.com/vishalchhodwani1992/httpLibrary
Related
I have to call one secured endpoint from rest client and at the controller side it require the authorities and user principal information to be sent from client.
String endpoint="http://localhost:8096/polygons/34";
// endpoint="https://dop-int.edosdp.ericsson.se/polygon-manager/polygons/34";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("mahi", "ChangeM6");
headers.setConnection("keep-alive");
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
ResponseEntity<Long> exchange = restTemplate.exchange(endpoint,HttpMethod.GET, httpEntity, Long.class);
how can send at least one role(ADMIN or GUEST_USER) information from client .
IS there any way I can wrap up all user info in a dummy session and send it to the serer.
Thanks ,
Mahi
No! It's a bad idea for the client to modify any kind of session information including cookies. Only the server should be allowed to do that.
Since your requirement is to check for user role on a specific url, you can set a custom request header and check for it within the controller method itself:
Example code:
#GetMapping("/polygons")
public String getPolygons(HttpServletRequest request) {
String userRole = request.getHeader("user-role");
if(userRole != null && userRole.toLowerCase().equals("admin")) {
System.out.print("Role provided: " + userRole);
// ...
return "some-data";
}
System.out.print("Role not provided!");
return "error";
}
You could also set the user role in the request body for a post request.
public class RequestParams {
private String userRole;
// ...
}
#PostMapping("/polygons")
public String getPolygons(#RequestBody RequestParams requestParams) {
String userRole = requestParams.getUserRole();
if(userRole != null && userRole.toLowerCase().equals("admin")) {
System.out.print("Role provided: " + userRole);
// ...
return "some-data";
}
System.out.print("Role not provided!");
return "error";
}
If your requirement is to check for the user role on multiple urls then you should consider writing a servlet filter.
EDIT:
I think I too faced a similar situation in the past. I ended up using apache's httpclient library instead of resttemplate.
Here's some sample code:
private List<OrganizationDTO> getUserOrgUnits(String loggedInUserId, String token) {
List<OrganizationDTO> userList = new ArrayList<OrganizationDTO>();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(getUserOrgUnitsApiURL());
try {
// Setting header
httpGet.setHeader("Authorization", "Bearer " + token);
httpGet.setHeader("Content-type", "application/json");
// Setting custom header
httpGet.setHeader(USERID_HEADER_NAME, loggedInUserId);
CloseableHttpResponse response = httpClient.execute(httpGet);
String result = EntityUtils.toString(response.getEntity());
JsonNode node = null;
ObjectMapper mapper = new ObjectMapper();
node = mapper.readTree(result);
Iterable<JsonNode> list = node.path("data");
for (JsonNode jsonNode : list) {
OrganizationDTO dto = mapper.treeToValue(jsonNode, OrganizationDTO.class);
userList.add(dto);
}
} catch (Exception e) {
log.error("getUserOrgUnits: Exception.");
e.printStackTrace();
}
return userList;
}
I send form data in POST request from angular app to my azure functions who wrriten in java.
the client side look like this:
#Injectable({
providedIn: 'root'
})
export class SendItemToAzureFunctionsService {
private functionURI: string;
constructor(private http: HttpClient) {
this.functionURI = 'https://newsfunctions.azurewebsites.net/api/HttpTrigger-Java?code=k6e/VlXltNs7CmJBu7lmBbzaY4tlo21lXaLuvfG/tI7m/XXXX';
}
// {responseType: 'text'}
sendItem(item: Item){
let body = new FormData();
body.append('title', item.title);
body.append('description', item.description);
body.append('link', item.link);
return this.http.post(this.functionURI, body)
.pipe(
map((data: string) => {
return data;
}), catchError( error => {
return throwError( 'Something went wrong!' );
})
)
}
}
when Item recived to azure functions.
the aim of functions is to send this item in push notifications via firebase to android app.
the azure functions with HTTP trigger look like this:
#FunctionName("HttpTrigger-Java")
public HttpResponseMessage run(#HttpTrigger(name = "req", methods = { HttpMethod.GET,
HttpMethod.POST }, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
// Parse query parameter
String itemDetails = request.getBody().get();
if (itemDetails == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Please pass a name on the query string or in the request body").build();
} else {
// ======
String postUrl = "https://fcm.googleapis.com/fcm/send";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
post.setHeader("authorization", FIREBAE_AUTH);
post.setHeader("Content-type", "application/json");
JSONObject contentJson = new JSONObject();
contentJson.put("title", "example title");
contentJson.put("description", "example text");
JSONObject pushNotificationJson = new JSONObject();
pushNotificationJson.put("data", contentJson);
pushNotificationJson.put("to", "/topics/newsUpdateTopic");
try {
StringEntity stringEntity = new StringEntity(pushNotificationJson.toString(), "UTF-8");
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
System.out.println(response.getEntity().getContent().toString());
} catch (IOException var9) {
var9.printStackTrace();
}
// =========
}
return request.createResponseBuilder(HttpStatus.OK)
.body("succeed to send new item in push notification to clients").build();
}
when I am running String itemDetails = request.getBody().get();
I am getting:
------WebKitFormBoundary2gNlxQx5pqyAeDL3
Content-Disposition: form-data; ....
I will be glad to know how to get data item from that?
If you want to parse from-date type data in Azure function with java, you can try to use MultipartStream in SDK org.apache.commons.fileupload to implement it. For example
code
public HttpResponseMessage run(
#HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) throws IOException {
context.getLogger().info("Java HTTP trigger processed a request.");
String contentType = request.getHeaders().get("content-type");
String body = request.getBody().get(); // Get request body
String boundary = contentType.split(";")[1].split("=")[1]; // Get boundary from content-type header
int bufSize = 1024;
InputStream in = new ByteArrayInputStream(body.getBytes()); // Convert body to an input stream
MultipartStream multipartStream = new MultipartStream(in, boundary.getBytes(), bufSize, null); // Using MultipartStream to parse body input stream
boolean nextPart = multipartStream.skipPreamble();
while (nextPart) {
String header = multipartStream.readHeaders();
int start =header.indexOf("name=") + "name=".length()+1;
int end = header.indexOf("\r\n")-1;
String name = header.substring(start, end);
System.out.println(name);
multipartStream.readBodyData(System.out);
System.out.println("");
nextPart = multipartStream.readBoundary();
}
return request.createResponseBuilder(HttpStatus.OK).body("success").build();
}
Test. I test with postman
I've used #Jim Xu's code and created a class to get the data in easier way. Here is the gist - https://gist.github.com/musa-pro/dcef0bc23e48227e4b89f6e2095f7c1e
I've been trying to mock Apache HTTPClient with ResponseHandler, in order to test my service, using Mockito. The method in question is:
String response = httpClient.execute(httpGet, responseHandler);
where "responseHandler" is a ResponseHandler:
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else {
log.error("Accessing API returned error code: {}, reason: {}", status, response.getStatusLine().getReasonPhrase());
return "";
}
};
Can somebody suggest how can I accomplish this? I want to mock "execute()" method, but I don't want to mock the "responseHandler" (I wan't to test the existing one).
Thanks!
You can mock HttpClient and use Mockito's thenAnswer() method. For example, something like:
#Test
public void http_ok() throws IOException {
String expectedContent = "expected";
HttpClient httpClient = mock(HttpClient.class);
when(httpClient.execute(any(HttpUriRequest.class), eq(responseHandler)))
.thenAnswer((InvocationOnMock invocation) -> {
BasicHttpResponse ret = new BasicHttpResponse(
new BasicStatusLine(HttpVersion.HTTP_1_1, HttpURLConnection.HTTP_OK, "OK"));
ret.setEntity(new StringEntity(expectedContent, StandardCharsets.UTF_8));
#SuppressWarnings("unchecked")
ResponseHandler<String> handler
= (ResponseHandler<String>) invocation.getArguments()[1];
return handler.handleResponse(ret);
});
String result = httpClient.execute(new HttpGet(), responseHandler);
assertThat(result, is(expectedContent));
}
I have created the Example Handler with AwsproxyRequest and response.
I am trying to zip this response with gzipping but in browser it is failing.
If I have added this same response in nodejs it is working fine.
public class ExampleHandler1 implements RequestHandler<AwsProxyRequest,AwsProxyResponse> {
#Override
public AwsProxyResponse handleRequest(AwsProxyRequest input, Context context) {
AwsProxyResponse response = new AwsProxyResponse(200, Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"), "Aaytu");
try {
HashMap<String, String> headermap = new HashMap<>();
headermap.put("Content-Encoding", "gzip");
headermap.put("Content-Type", "text/html");
String responseString = Base64.getMimeEncoder().encodeToString(GzipCompressor.compress("Hello there..!!!").getBytes());
AwsProxyResponse retVal = new AwsProxyResponse(200, headermap, responseString);
retVal.setBase64Encoded(true);
return retVal;
} catch (Exception e) {
}
return response;
}
}
I am working on an Android project in which I want to create a RESTful POST connection to a Spring-MVC based server. I initially tried to post an object but I used to get errors. That is why I tried to send a JSON object. Currently I don't get any errors in the Android app, but when I receive the JSON object and get the String, there is nothing in the JSON object.
I debugged the code to see that values are being sent correctly. I don't know what I am doing wrong. Any help would be nice. Thanks a lot.
Android code to send object :
#Override
public void addRestaurant(Restaurant restaurant) {
Log.d("Restaurant Name",restaurant.getRestaurantName());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Looper.prepare();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),10000);
HttpResponse response;
JSONObject jsonObject = new JSONObject();
HttpPost post = new HttpPost(url);
jsonObject.put("restaurantName",restaurant.getRestaurantName());
jsonObject.put("postLeitZahl",restaurant.getPostLeitZahl());
jsonObject.put("phoneNumber",restaurant.getPhoneNumber());
jsonObject.put("id",restaurant.getId());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/JSON"));
post.setEntity(stringEntity);
response = client.execute(post);
} catch (Exception e){
e.printStackTrace();
}
Looper.loop();
//String response = restTemplate.postForObject(url,restaurant,String.class);
//Log.d(response,"Response from webserver is");
}
});
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
}
}
Spring Controller code :
#RequestMapping(value = "/restaurant/add",method = RequestMethod.POST,consumes="application/json")
#ResponseBody
public String addRestaurantWebView(JsonObject restaurant){
System.out.println(restaurant.getAsString());
return "true";
}
I don't know what I am doing wrong and I am having trouble finding some resources which can tell me how to configure the server according to the code in android or vice-versa. Thanks a lot ..:-)
Edit (Solution)(Partial with Java Objects)
As my original intention was to send a Java object which was failing, I reverted to JSON, but later it worked with Java, here is the Android code and the Spring-MVC Controller and bean which worked for me.
Android code :
package com.example.myapp;
import android.os.Process;
import android.util.Log;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class RestaurantServiceImpl implements RestaurantService {
String url = "http://192.168.178.40:8080/restaurant/add";
#Override
public void addRestaurant(Restaurant restaurant) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(restaurant,headers);
ResponseEntity<String> out = restTemplate.exchange(url, HttpMethod.POST,entity,String.class);
Log.d(out.toString(),"Response from server");
} catch (Exception e){
e.printStackTrace();
}
}
});
thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
}
}
Spring-MVC controller :
#RequestMapping(value = "/restaurant/add",method = RequestMethod.POST)
#ResponseBody
public String addRestaurantWebView(#RequestBody Restaurant restaurant){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("restaurant", new Restaurant());
modelAndView.addObject(restaurant);
this.restaurantService.addRestaurant(restaurant);
return "true";
}
Servlet-context.xml
Add this :
<mvc:annotation-driven />
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:ref bean="jsonMessageConverter"/>
</beans:property>
</beans:bean>
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
This is how I would do: create the class Restaurant on you're Spring app. Then use it as the parameter in the request mapping with #ModelAttribute:
public String addRestaurantWebView(#ModelAttribute Restaurant restaurant) {
Then, on Android send the parameters with a MultipartEntity:
Charset charset = Charset.forName("UTF-8");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, charset);
entity.addPart("restaurantName", new StringBody(restaurant.getRestaurantName(), charset));
entity.addPart("postLeitZahl", new StringBody(restaurant.getPostLeitZahl(), charset));
entity.addPart("phoneNumber", new StringBody(restaurant.getPhoneNumber(), charset));
entity.addPart("id", new StringBody(restaurant.getId(), charset));
HttpPost post = new HttpPost(url);
post.setEntity(entity);
response = client.execute(post);