Da es für Java jede Menge unterschiedliche Implementierungen eines HTTPClient gibt, hier mal ein Beispiel für die die Variante der Apache Foundation die im Google Android SDK zum Einsatz kommt. In diesem Beispiel geht es darum sich auf einem entfernten Server einzuloggen und anschließend Daten via JSON abzufragen und wieder in getypte Java Objekte umzuwandeln. Dabei speichert der Server den Login-Status in einer Session. Die SessionID wird auf der Clientseite in einem Cookie gespeichert, und muss bei jeder Anfrage mitgesendet werden.
Funktionsweise
Verbindung herstellen
HttpGet get = new HttpGet(String.format("%s?username=%s&password=%s", loginUrlHost, user, pass)); DefaultHttpClient client = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse response = client.execute(get);
Anwort auswerten
int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { String responseText = responseHandler.handleResponse(response); }
JSON parsen
import org.json.JSONException; import org.json.JSONObject; public class LoginResponse extends JSONObject { private boolean success; private String message; public LoginResponse(String string) throws JSONException { super(string); success = getBoolean("success"); message = (get("message").equals(null))?"":getString("message"); } public boolean isSuccess() { return success; } public String getMessage() { return message; } }
LoginResponse loginResponse; try { loginResponse = new LoginResponse(responseText); } catch (JSONException e) { Log.d("LOGIN_ERROR(INVALID_RESPONSE)", e.getMessage(), e); errorState = INVALID_RESPONSE; return INVALID_RESPONSE; }
Cookies auslesen
List<Cookie> cookies = client.getCookieStore().getCookies(); for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); Log.d("Cookie-Name:", cookie.getName()); Log.d("Cookie-Value:", cookie.getValue()); break; }
Cookies senden
DefaultHttpClient client = new DefaultHttpClient(); CookieStore cookieStore = client.getCookieStore(); cookieStore.addCookie(loginCookie); client.setCookieStore(cookieStore);