florin88
Messaggi : 334 Data d'iscrizione : 21.09.11 Età : 35 Località : tutto il mondo
| Titolo: Script Andorid per effettuare una richiesta di tipo HTTP con Credenziali Dom Ott 23, 2011 10:44 pm | |
| Questo scritp per Android vi permette di implementare all'interno della vostra app la possibilità di effettuare una richiesta http con credenziali. - Codice:
-
private String mServer; private String mServerUrl; private int mPort = 8551; private String mUser; private String mPassword; private HttpResponse makeRequest(String urlPath) throws Exception { HttpClient httpclient; HttpParams httpParameters; HttpGet request; int timeoutConnection = 10000; int timeoutSocket = 10000; httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); httpclient = new DefaultHttpClient(httpParameters); Credentials creds = new UsernamePasswordCredentials(mUser, mPassword); ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials( new AuthScope(mServer, mPort), creds); request = new HttpGet(mRequestURL); HttpResponse res = httpclient.execute(request); httpclient.getConnectionManager().shutdown(); return res; } private String processRequest(HttpResponse resp) throws Exception{ int status = resp.getStatusLine().getStatusCode(); if (status == 200){ //Get the body return getBodyFromResponse(resp); } else if (status == 400) { //Bad Request throw new Exception("Errore: errore HTTP 400"); } else if (status == 401) { //Unauthorized throw new Exception("Errore: errore HTTP 401 - nome server errato"); } else if (status == 403) { //Forbidden throw new Exception("Errore: HTTP 403 } else if (status == 500) { //Internal Server Error throw new Exception("Errore: HTTP 500"); } else { throw new Exception("Errore sconosciuto: Lo status " + status); } } private String getBodyFromResponse(HttpResponse resp) throws Exception{ ResponseHandler<String> handler = new BasicResponseHandler(); try { return handler.handleResponse(resp); } catch (IOException e) { throw new Exception ("Errore HTTP 200. Errore conversione. " + e.getMessage()); } catch (Exception e) { throw new Exception ("Error: HTTP 200. Errore conversione. " + e.getMessage()); } }
Buon Lavoro |
|