Android data storage network storage data

Android Async HTTP

The simplest and most basic use of android-async-http only requires the following steps:

  1. Create an AsyncHttpClient;

  2. (Optional) Set request parameters through the RequestParams object;

  3. Call a get method of AsyncHttpClient and pass the callback interface implementation you need (success and failure), which are generally anonymous inner classes that implement AsyncHttpResponseHandler. The class library itself also provides many ready-made response handlers, you generally do not need to create them yourself

The AsyncHttpClient class is usually used in android applications to create asynchronous GET, POST, PUT and DELETE HTTP requests. The request parameters are created through the RequestParams instance, and the response is handled by overriding the anonymous inner class ResponseHandlerInterface method.

The following code shows the basic operation of using AsyncHttpClient and AsyncHttpResponseHandler:

AsyncHttpClient client = new AsyncHttpClient();
        String path = "";
        RequestParams params = new RequestParams();
        params.put("username", username);
        params.put("password", password);
        client.get(path, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

 

try {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("username", "ryantang");
    StringEntity stringEntity = new StringEntity(jsonObject.toString());
    client.post(mContext, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){
        @Override
        public void onSuccess(JSONObject jsonObject) {
            super.onSuccess(jsonObject);
        }
    });
} catch (JSONException e) {
    e.printStackTrace ();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace ();
}

 

HttpUrlConnection

  HttpUrlConnection is an API provided in the Java .NET package. We know that the Android SDK is based on Java, so of course, the most primitive and most basic API, HttpUrlConnection, is given priority. In fact, most open source networking frameworks are basically based on JDK's HttpUrlConnection. Encapsulation is enough, mastering HttpUrlConnection requires the following steps: 
   
1. Convert the accessed path into a URL.

URL url = new URL(path);

2. Get the connection through the URL.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

3. Set the request method.

conn.setRequestMethod(GET);

4. Set the connection timeout time.

conn.setConnectTimeout(5000);

5. Set the request header information.

conn.setRequestProperty(User-Agent, Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0));

7. Do different operations for different response codes (the request code is 200, indicating that the request is successful, and the input stream of the returned content is obtained)

Tools:

public class StreamTools {
    /**
     * Convert input stream to string
     *
     * @param is
     * The input stream obtained from the network
     * @return
     */
    public static String streamToString(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len ​​= 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            return null;
        }
    }
}

HttpUrlConnection sends a GET request

public static String loginByGet(String username, String password) {
        String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username= + username + &password= + password;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod(GET);
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream(); // convert byte stream to string
                return StreamTools.streamToString(is);
            } else {
                return network access failed;
            }
        } catch (Exception e) {
            e.printStackTrace ();
            return network access failed;
        }
    }

HttpUrlConnection sends POST request

public static String loginByPost(String username, String password) {
        String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod(POST);
            conn.setRequestProperty(Content-Type, application/x-www-form-urlencoded);
            String data = username= + username + &password= + password;
            conn.setRequestProperty(Content-Length, data.length() + );
            // POST method, in fact, the browser writes data to the server
            conn.setDoOutput(true); // set the output stream
            OutputStream os = conn.getOutputStream(); // Get the output stream
            os.write(data.getBytes()); // write data to server
            int code = conn.getResponseCode();
            if (code == 200) {
                InputStream is = conn.getInputStream();
                return StreamTools.streamToString(is);
            } else {
                return network access failed;
            }
        } catch (Exception e) {
            e.printStackTrace ();
            return network access failed;
        }
    }

 

HttpClient

  HttpClient is a Java request network framework provided by the open source organization Apache. It was first born to facilitate the development of Java servers. It encapsulates and simplifies the APIs of HttpUrlConnection in JDK, improves performance and reduces the tediousness of calling APIs. Therefore, this networking framework is also introduced, and we can use it directly without importing any jar or class library. It is worth noting that the Android official has announced that HttpClient is not recommended.

HttpClient sends GET request

1. Create HttpClient object

2. Create an HttpGet object and specify the request address (with parameters)

3. Use the execute() method of HttpClient to execute the HttpGet request and get the HttpResponse object

4. Call the getStatusLine().getStatusCode() method of HttpResponse to get the response code

5. Call getEntity().getContent() of HttpResponse to get the input stream and get the data written back by the server

public static String loginByHttpClientGet(String username, String password) {
        String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username=
                + username + &password= + password;
        HttpClient client = new DefaultHttpClient(); // Enable network access client
        HttpGet httpGet = new HttpGet(path); // wraps a GET request
        try {
            HttpResponse response = client.execute(httpGet); // client executes the request
            int code = response.getStatusLine().getStatusCode(); // Get the response code
            if (code == 200) {
                InputStream is = response.getEntity().getContent(); // get entity content
                String result = StreamTools.streamToString(is); // byte stream to string
                return result;
            } else {
                return network access failed;
            }
        } catch (Exception e) {
            e.printStackTrace ();
            return network access failed;
        }
    }

 

HttpClient sends POST request

1. Create HttpClient object

2. Create an HttpPost object and specify the request address

3. Create a List to load parameters

4. Call the setEntity() method of the HttpPost object, load a UrlEncodedFormEntity object, and carry the previously encapsulated parameters

5. Use the execute() method of HttpClient to execute the HttpPost request and get the HttpResponse object

6. Call the getStatusLine().getStatusCode() method of HttpResponse to get the response code

7. Call getEntity().getContent() of HttpResponse to get the input stream and get the data written back by the server

public static String loginByHttpClientPOST(String username, String password) {
        String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
        try {
            HttpClient client = new DefaultHttpClient(); // create a client
            HttpPost httpPost = new HttpPost(path); // wraps the POST request
            // Set the sent entity parameters
            List parameters = new ArrayList();
            parameters.add(new BasicNameValuePair(username, username));
            parameters.add(new BasicNameValuePair(password, password));
            httpPost.setEntity(new UrlEncodedFormEntity(parameters, UTF-8));
            HttpResponse response = client.execute(httpPost); // execute POST request
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                InputStream is = response.getEntity().getContent();
                String result = StreamTools.streamToString(is);
                return result;
            } else {
                return network access failed;
            }
        } catch (Exception e) {
            e.printStackTrace ();
            return access to the network failed;
        }
    }

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326413668&siteId=291194637