简易的封装了的HTTP的GET和POST类,并封装到AsyncTask线程中

在安卓开发中,经常会涉及到网络访问以交换数据,因此,这里把我正在写的项目中的HTTP类抽取出来,方便以后使用。

HTTP.java:

import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * Created by gyh on 17-7-27.
 */
public class HTTP {
    public static String HttpGet(String Url) {
        /*Usage:
        String str=HTTP.HttpGet(url);
        url is the endpoint.
         */
        HttpURLConnection connection = null;
        String str = null;
        try {
            URL url = new URL(Url);
            connection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(connection.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            str = "";
            String len;
            while ((len = br.readLine()) != null) {
                //while the data stream is not ended
                str = str + len;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null)
                connection.disconnect();
        }
        //the value of str is what you need
        Log.d("data", str);
        return str;
    }
    public static String HttpPost(String Url, String data) {
        /*Usage:
        String str=HTTP.HttpPost(url,data);
        url is the endpoint, and data is the data you want to post, format like "user=user&pwd=pwd".
         */
        HttpURLConnection urlConnection = null;
        String str = null;
        try {
            URL url = new URL(Url);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            str = "";
            String len;
            while ((len = br.readLine()) != null) {
                //while the data stream is not ended
                str = str + len;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
        }
        return str;
    }
}

并且,在安卓5.0之后,不允许在主线程中进行网络访问,这里,再将它封装到线程中。

以Login活动为例:

    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        private final String mEmail;
        private final String mPassword;
        private String token;
        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
//TODO replace you url
                String api = "You url address here";
                String data = "user=" + mEmail + "&pwd=" + mPassword;
                String res = HTTP.HttpPost(api, data);
                JsonParser parser = new JsonParser();
                JsonObject json = (JsonObject) parser.parse(res);
                if (json.get("status").getAsString().equals("error")) {
                    return false;
                }
                token = json.get("token").getAsString();
            } catch (Exception e) {
                return false;
            }
            SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("user", mEmail);
            editor.putString("token", token);
            editor.apply();
            editor.commit();
            return true;
        }
        @Override
        protected void onPostExecute(final Boolean success) {
            mLoginTask = null;
            showProgress(false);
            if (success) {
                Toast toast = Toast.makeText(getWindow().getDecorView().findViewById(android.R.id.content).getContext(),
                        getString(R.string.login_success), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                finish();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }
        @Override
        protected void onCancelled() {
            mLoginTask = null;
            showProgress(false);
        }
    }

0 条评论
发表一条评论