I am doing a REST client in Android to consume a webService hosted in Amazon EC2.
When a acess the URL in bowser, it's work fine. But when i tried to acess the webservice in the android app, i received a error 404.
URL urla = new URL(SERVICE_URL);
HttpGet method= new HttpGet(new URI(SERVICE_URL));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(SERVICE_URL));
HttpResponse response = client.execute(method);
int responseCode = response.getStatusLine().getStatusCode();
When I provide the rule "All" Access In the amazon EC2, it's work fine, but i believe it's not a better way.
All Rule:
*Ports: All
Protocol: All
Source: All*
Does anyone know a better way to access the REST webservice hosted in the EC2 with a client android?
Try using AsyncHttpClient library instead thats simple and easy. Here is a sample code
AsyncHttpClient client;
client.get("http://ec2-xx-xxx-xx-xx.compute-1.amazonaws.com:8080/MyService1/jaxrs/helloworld",
new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
#Override
public void onSuccess(String response) {
try {
// JSON Object
tv1.setText(response);
} catch (Exception e) {
tv1.setText(e.getMessage());
}
}
});
Simple give the public DNS of your instance with port of server, then path to the function call of your service.
This is how I did it.
Related
In my android application I try to send a json object to a distant server, when I run it I get an error in httpclient.execute(httpPost)
This is a part of my code.
public static String GET(String url , JSONObject js){
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "Basic **********");
httpPost.setEntity(new StringEntity(js.toString()));
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (Exception e) {
Log.i("Console", "Error");
}
Any help please.
I guess your Problem is, that you try to run your Network Request from your Main Thread.
I would discourage you to use the Apache HTTP Client at all.
It became deprecated for Marshmallow, see here
Maybe try OkHttp. It offers you the possibility to run a request asynchronously.
Hi this is my HTTP Post Request Method in Android client.i don't know how to implement the #POST method in the Restful web server.
public class AndroidHTTPRequestsActivity extends Activity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://localhost:8080/GPS_Taxi_Tracker_Web_Server/resources/rest.android.taxi.androidclientlocation/Login");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user#gmail.com"));
nameValuePair.add(new BasicNameValuePair("message",
"Hi, trying Android HTTP post!"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
what is the implementation for the post method in the java restful web service , this is my code for the Rest sever what is wrong ?
#POST
#Path("{Login}")
#Consumes({"application/xml"})
public void Add(#PathParam("email") String email,AndroidClientLocation entity) {
entity.setEmail(email);
super.create(entity);
}
Multiple questions..
What are you using as container on server side
What is your base url mapping. Your API method's path being Login, how do are you routing the remaining part of the URL (/resources/rest.android.taxi.androidclientlocation) to the API.
The API consumes application/xml but the client code is not sending/setting Content-Type as application/xml, is it taken care by the client?
When you run the request from client what is the response (HTTP Error) that you get.
Where is your REST server running (Internal or External).
Answers to the question might clarify the request a bit more.
http://developer.android.com/tools/devices/emulator.html#networkaddresses
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
http://localhost:8080/.
as per link & link2
Send a request to localhost' means to send it to the local machine. In your case that would be the Android device. You want to send the request to your desktop machine, which is a remote host. The problem is that the Appengine dev_sever by default only binds to the local address, so it can't be accessed remotely (i.e., from your Android device). You need to pass the --address option to make accessible from the outside. Check your computer's IP and pass it as the address. Something like:
dev_appserver.cmd --address=192.168.2.220
I am developing a Android app, which communicates with a RESTful WCF Web Service in my server.
By using HttpClient, the application can read the json code from a url link.
For Example:
http://www.example.com/WebService/Service.svc/subscriptions/tiganeus
returns {"JSONUserDataResult":["Application A","Application B"]}
However, this web service itself is anonymous accessible, but protected by ISA Server.
Browser automatically shows "Authentication Required" dialog when this link is accessed externally. Simply fill in the username and password is OK.
I figured out how to do authentication in a webview. The following code works
private class MyWebViewClient extends WebViewClient {
#Override
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.proceed("username", "password");
System.out.println("httpa");
}
}
But what I really need is to read the JSON code from the url.
I have chosen to use HttpClient to do the job, but I can't figure out how to authenicate within the HttpClient. It sounds simple as any browser can do it.
Any help will be appreciated.
Apparently it is much simpler than I thought.
DefaultHttpClient() httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new NTCredentials(user, pass, "tamtam", "tamtam"));
URI uri = new URI("http://www.example.com/WebService/Service.svc/subscriptions/tiganeus");
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Content-type", "application/json; charset=utf-8");*/
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
String result = EntityUtils.toString(responseEntity);
httpClient.getCredentialsProvider().setCredentials works fine for the authentification through isa server
(at least for in the way my isa-server is configured.
It handles basic authentication as well.
I am trying to invoke a private web-service in which there's one link I've to access using GET method. While using the direct URL on browser (needs to login first), I get the data in JSON format. The URL I am invoking is like this
http://www.example.com/trip/details/860720?format=json
The url is working fine, but when I invoke this using HttpGet, I am getting the HTML coding of the webpage, instead of the JSON String. The code I am using is as follows:
private String runURL(String src,int id) { //src="http://www.example.com/trip/details/"
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(src);
String responseBody="";
BasicHttpParams params=new BasicHttpParams();
params.setParameter("domain", token); //The access token I am getting after the Login
params.setParameter("format", "json");
params.setParameter("id", id);
try {
httpget.setParams(params);
HttpResponse response = httpclient.execute(httpget);
responseBody = EntityUtils.toString(response.getEntity());
Log.d("runURL", "response " + responseBody); //prints the complete HTML code of the web-page
} catch (Exception e) {
e.printStackTrace();
}
return responseBody;
}
Can you tell me what am I doing wrong here??
Try specify Accept & Content-Type in you http header:
httpget.setHeader("Accept", "application/json"); // or application/jsonrequest
httpget.setHeader("Content-Type", "application/json");
Note that you can use tools like wireshark capture and analyse the income and outcome http package, and figure out the exact style of the http header that returns your json response from a standard browser.
Update:
You mentioned need login first when using browser, the html content returned is probably the login page (if use basic authentication type, it returns a short html response with status code 401, so a modern browser knows how to handle, more specifically, pop up login prompt to user), so the first try would be checking the status code of your http response:
int responseStatusCode = response.getStatusLine().getStatusCode();
Depend on what kind of authentication type you use, you probably need specify login credentials in your http request as well, something like this (if it is a basic authentication):
httpClient.getCredentialsProvider().setCredentials(
new AuthScope("http://www.example.com/trip/details/860720?format=json", 80),
new UsernamePasswordCredentials("username", "password");
How can I get the principal name, session and ideally check if the principal is authenticated with the Spring Security context inside a CXF JAX-RS webservice method receiving a call from an Android client? This is the code I am currently working with. I have commented where and what I am trying to get.
Android code to call webservice:
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("192.168.1.101", 80),
new UsernamePasswordCredentials("joesmith", "mypasswd"));
HttpGet httpget = new HttpGet(WEBSERVICE_URL+"/makePayload");
httpget.setHeader("User-Agent", userAgent);
httpget.setHeader("Content-Type", "application/xml");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
... parse xml from response
}
CXF, Spring webservice code:
#GET
#Path("/getPayload")
#Produces("application/XML")
public Response makePayload(#Context Request request){
//Get user principal name
//Get session?
//Get Spring security context?
Payload payload = new Payload();
payload.setUsersOnline(new Long(200));
return Response.ok().entity(payload).build();
}
request.getUserPrincipal.getName() or static SecurityContextHolder.getContext().getAuthentication().getName() might work