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.
Related
How to save and retrieve data from database. Can somebody give me a little help how to connect web service with database and in app, what would be the first step to start. Thanks.
Build a web server, which will be sending the JSon objects to you
Then use http calls to get this Json, like this:
public String httpGet(String url) throws IOException{
HttpGet get = new HttpGet(url);
DefaultHttpClient() _httpClient = new DefaultHttpClient();
BasicHttpContext httpContext = new BasicHttpContext();
HttpResponse response=null;
response = httpClient .execute(get, httpContext);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
return EntityUtils.toString(response.getEntity());
}
For more information, leave me a message, please.
To communicate with a remote database: database on server for example you need to communicate with an API. They are several ways to build an API: PHP, ruby.
Communicating with a remote db is forbidden in most of hosts for security purpose.
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.
I am accessing a REST web service via Mozilla client via Mozilla browser. (In web service
back end spring security has configured and credentials for each
request is validated). So I am setting basic authentication (username and password) and
Request header "application/json" which is fine.
Now I want to connect to this web service via a android application as below. How do I set
credentials of the user (username and password) to the request ?
#Override
protected Void doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
WsUrl="http://192.168.0.15:8080/ServiceApp/categoryservice/category/001"; // RESTFUL URL RESOURCE
HttpGet getRequest = new HttpGet(WsUrl);
try {
HttpResponse response=client.execute(getRequest);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode != 200){
return null;
}
InputStream jsonStream = response.getEntity().getContent();
ufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
check the link for answer, I don't what kind of authentication you are using, but this link shows how to windows basic authentications
HTTP requests with basic authentication
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