Code example for HttpURLConnection

Methods: addRequestProperty, connect, getResponseCode, getResponseMessage, setConnectTimeout, setDoInput, setReadTimeout, setRequestMethod

0
    private HttpURLConnection prepareGet(String apiPath, boolean withToken)
            throws IOException { 
        URL url = new URL(account.server + apiPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        prepareSSL(conn, true);
        conn.setReadTimeout(30000);
        conn.setConnectTimeout(15000);
     
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        if (withToken)
            conn.addRequestProperty("Authorization", "Token " + account.token);
         
        //Log.d(DEBUG_TAG, "get from " + url.getPath()); 
        return conn;
    } 
     
    private HttpURLConnection prepareGet(String apiPath) throws IOException {
        return prepareGet(apiPath, true);
    } 
     
    private HttpURLConnection prepareFileGet(String urlString)
            throws IOException { 
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        prepareSSL(conn, false);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        return conn;
    } 
     
    private  HttpURLConnection preparePost(String apiPath, boolean withToken)
            throws IOException { 
        URL url = new URL(account.server + apiPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        prepareSSL(conn, true);
         
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
         
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        if (withToken)
            conn.addRequestProperty("Authorization", "Token " + account.token);
        return conn;
    } 
     
    private  HttpURLConnection preparePost(String apiPath) throws IOException {
        return preparePost(apiPath, true);
    } 
     
    private String encodePostParams(List<NameValuePair> params)
            throws UnsupportedEncodingException { 
        StringBuilder result = new StringBuilder();
        boolean first = true;
 
        for (NameValuePair pair : params) {
            if (first)
                first = false;
            else 
                result.append("&");
             
            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        } 
 
        return result.toString();
    } 
     
    private void doPost(HttpURLConnection conn, List<NameValuePair> params) 
            throws IOException, ProtocolException, UnsupportedEncodingException { 
        OutputStream os = null;
        try { 
            os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    os, "UTF-8"));
            writer.write(encodePostParams(params));
            writer.close(); // must call this to actually write to the output
            conn.connect();
        } finally { 
            try { 
                if (os != null)
                    os.close();
            } catch (Exception e) {
                // ignore 
            } 
        } 
    } 
     
     
    /** 
     * Login into the server 
     * @return true if login success, false otherwise 
     * @throws IOException 
     */ 
    public boolean doLogin() throws SeafException { 
        InputStream is = null;
 
        try { 
            HttpURLConnection conn = preparePost("api2/auth-token/", false);
 
            Log.d(DEBUG_TAG, "Login to " + account.server + "api2/auth-token/");
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", account.email));
            params.add(new BasicNameValuePair("password", account.passwd));
            doPost(conn, params);
 
            if (conn.getResponseCode() != 200)
                throw new SeafException(conn.getResponseCode(), conn.getResponseMessage());
 
            is = conn.getInputStream();
            String contentAsString = Utils.readIt(is);
            JSONObject obj = Utils.parseJsonObject(contentAsString);
            if (obj == null)
                return false; 
            account.token = obj.getString("token");
            return true; 
        } catch (SeafException e) {
            throw e;
        } catch (SSLException e) {
            throw SeafException.sslException; 
        } catch (IOException e) {
            e.printStackTrace();
            throw SeafException.networkException; 
        } catch (JSONException e) {
            throw SeafException.illFormatException; 
        } finally { 
            // Makes sure that the InputStream is closed after the app is 
            // finished using it. 
            try { 
                if (is != null) {
                    is.close();
                } 
            } catch (Exception e) {
                // ignore 
            } 
        } 
    } 
     
    public boolean authPing() throws SeafException { 
        InputStream is = null;
        try { 
             
            HttpURLConnection conn = prepareGet("api2/auth/ping/");
             
            // Starts the query 
            conn.connect();
            int response = conn.getResponseCode();
            if (response != 200)
                throw new SeafException(response, conn.getResponseMessage());
             
            is = conn.getInputStream();
            String result = Utils.readIt(is);
            if (result.equals("\"pong\""))
                return true;