HTTPS request/response in Android - android

Need to send a POST request to a Service provider using HTTPS protocol, response from the service provider will be an xml file, need to read that also.

You could start by taking a look at AndroidHttpClient and at HttpPost.
Something like this should work:
final AndroidHttpClient httpClient = AndroidHttpClient.newInstance(this.getClass().getSimpleName());
HttpResponse httpresponse = null;
HttpEntity httpentity = null;
HttpUriRequest httprequest = new HttpPost("https://...");
byte[] xmlByteArray = null;
if ((httpresponse = httpClient.execute(httprequest)) != null) {
if ((httpentity = httpresponse.getEntity()) != null) {
xmlByteArray = EntityUtils.toByteArray(httpentity);
}
}
Also, my RestClient on github might be useful.
Note: I use GET to retrieve the data, so YMMV.

Related

How to make a web request sending a HASH key and get a Response Android

I've searched everywhere on how to make this happen but with no results.
First I need to make a request to a website then send a hash (which I already have) and get a response with some data.
I was able to connect but I'm not able to use the hash key to get the data.
Can anyone help me how to do this using android?
Thanks.
I tried to follow this:Make an HTTP request with android
using a host
The solution:
final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(URL);
postMethod.setEntity(new StringEntity(postData, "utf-8"));
String responseData = "";
try {
final HttpResponse response = client.execute(postMethod);
responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
// handle exception here
}
This is an example of what you can do:
final String URL = "http://192.168.0.100:8000/myHistory/mobile/?user=";
HttpClient client;
StringBuilder url = new StringBuilder(URL);
url.append(user);
url.append("&pwd=");
url.append(hash);
client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse response = null;
try {
response = client.execute(get);
} catch (IOException e) {
e.printStackTrace();
}
int status = 0;
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = "";
try {
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//Here you manipulate the 'data' variable, which is in HTML format.
It depends on which kind of hash you are using (SHA-N, MD5, etc) and the kind of framework you are using to build the server. Try to search on the documentation of your framework which kind of cryptographic hash function is used. Then search on internet an API that implements this cryptographic hash function on your code (e.g., Django uses PBKDF2). After that, you need to define the parameters of this function (salt, number of iterations, password (or hash)). The algorithm calculates the hash (password) using the salt and number of iterations values. So when you are trying to access a server you have to send via HTTP the hash that was generated. If this hash is the same hash generated on the server side, then the authentication is successful.

Android HttpClient to accept all cookies

I'm pretty new in the Android world and maybe my question is very simple..
I have an android app where I use HttpGet to connect to a server and collect data.
However the server sometimes sets some cookies that are not remembered by my code.
I found a post where its using a custom cookie policy and is accepting everything.. just what I need.But I cant implement it.As I understand my version of java httpclient is old and does not have the functions I need.
Here's my code:
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(link);
get.getParams().setParameter(
ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse responseGet = client.execute(get,ctx);
status_code = responseGet.getStatusLine().getStatusCode();
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
http_response = EntityUtils.toString(resEntityGet);
}
}
And the code I need to implement:
CookieStore cookieStore = new BasicCookieStore();
httpclient.setCookieStore(cookieStore);
CookieSpecFactory csf = new CookieSpecFactory() {
public CookieSpec newInstance(HttpParams params) {
return new BrowserCompatSpec() {
#Override
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
log.debug("allow all cookies");
}
};
}
};
httpclient.getCookieSpecs().register("easy", csf);
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, "easy");
All I need is to set this csf policy to my client.
However it seems that I dont have these two functions in the library : setCookieStore and getCookieSpecs().register()
What are my options to run it ?!

how to use JSON responce in a url

i am developing an android application with RESTful WebServices
suppose ,
i am sending a url http request as somewebservice/data/access
and is sends data as {"serviceMessageCode":1,"serviceMessageText":"aaaaaa","items":null}
and i want to send another request with that obtained key as
somewebService/rest/services/secure/getcategories?apikey=aaaaaa
int sMC = jsonObj.getInt("serviceMessageCode");
if (sMC == 1) {
smt = jsonObj.getString("serviceMessageText");
can i use somewebService/rest/services/secure/getcategories?apikey=smt
i think i should not do so , some one tell me how to achieve this..!!
please help....
There is no reason why you could not pass some data by GET parameters. It really depends on Rest API on your backend server. Do you use any REST client or base apache http package classes to make requests to server?
Edited:
BufferedReader in = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
String uri = String.format("http://somewebService/rest/services/secure/getcategories?apikey=%s", Config.API_KEY); // API_KEY is constant value written somewhere or could you pass it as method argument
URI website = new URI(uri);
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
StringBuilder builder = new StringBuilder();
while(null != (line = in.readLine())) {
builder.append(line);
}
in.close();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}

Android: Getting HTTP response incrementally like in iOS

I'm relatively new to Android (I'm an iOS-Developer) and I want to call a Webservice like I'm used to in iOS with NSURLConnectionDelegate's method
didReceiveData:(NSData *)data
I need to get the data incrementally because I'm building a streaming API that gets a lot of JSON data in response and needs to check the data for complete blocks.
Would be great if someone could help me, I've been searching for a while and didn't find a satisfying solution so far.
If you try to call web services in Android you should use the AsyncTask where the request would be made asynchronously. Have a look at the documentation. Every time you're request would be finished the method onPostExecute(Object result) would be called. Thats the method where you can go on with further processes.
The URLConnection documentation contain following example:
URL url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
readStream(in);
finally {
in.close();
}
If i right understood your question, just implement readStream function as you need.
I found out how to do this with the help of a friend and some links.
You need to implement an own ResponseHandler like this:
class ChunkedResponseHandler implements ResponseHandler<String> {
#Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
StringBuffer output = new StringBuffer();
byte[] b = new byte[4096];
int n;
while ((n = stream.read(b)) != -1) {
output.append(new String(b, 0, n));
// do something while input is streaming
}
return output.toString();
}
}
Now you simply have to assign the response handler when starting the request:
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("someURL");
ResponseHandler<String> responseHandler = new ChunkedResponseHandler();
String responseBody = client.execute(postRequest, responseHandler);

Android - How to realize REST GET function for REST API in skydrive

Does anyone know how to use Skydrive REST API in Android?
(documented here http://msdn.microsoft.com/de-de/library/live/hh243648.aspx)
All Data that are needed for access are already stored!
private String AccessToken;
private String AuthenticationToken;
private String RefreshToken;
private String ExpiresIn;
private String Scope;
Is it right to use
HttpClient client = new DefaultHttpClient();
Does anyone have a full example?
Any ideas or suggestion would be helpful. Thank you.
You can do something like this.
InputStream result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("https://apis.live.net/v5.0/me/albums?access_token=" + AccessToken); // For example
HttpResponse response = httpClient.execute(get);
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
result = bufferedHttpEntity.getContent();
} else {
// insert error handling
}
Depending on what request you are making you may need to use HttpPut, HttpPost, HttpDelete, etc. instead of HttpGet.
GET - Returns the representation of a resource.
POST - Adds a new resource to a collection.
PUT - Updated to the location that was specified as the target URL, or add a resource there, add a resource if one does not exist.
DELETE - Deletes a resource.
If the request requires a body, you can add it with setEntity() which takes an HttpEntity object.

Categories

Resources