手记

安卓中使用HttpURLConnection进行增删改查操作(包括后端讲解)(二)

我们在上一节https://www.imooc.com/article/267427点击一个item,就可以去编辑书本的名字


这个页面可以进行编辑,新增和删除的功能

public class BookDetail extends Activity {

    public static final String TAG = TestHttpActivity.class.getSimpleName();
    private TextView mBookName;
    private EditText mBookNameEdit;
    private boolean isAddOrEdit;
    private LinearLayout description_layout;
    private EditText mDescriptionEdit;
    private Book mBook;
    private TitleBarCommon mTitleBarCommon;

    public static void startActivity(Context context, Book book) {
        Intent intent = new Intent();
        intent.putExtra("book",book);
        intent.setClass(context,BookDetail.class);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.book_detail);
        initTitle();
        Intent intent = getIntent();
        mBook = (Book)intent.getSerializableExtra("book");
        mBookName = (TextView)findViewById(R.id.bookName);
        mBookNameEdit = (EditText)findViewById(R.id.bookname_edit);
        mDescriptionEdit = (EditText) findViewById(R.id.bookdescription_edit);
        TextView mSaveBtn = (TextView)findViewById(R.id.save_tv);
        mSaveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new InitDataAsyncTask(mBook).execute();
            }
        });

        description_layout = (LinearLayout)findViewById(R.id.description_layout);
        if(mBook == null) {
            description_layout.setVisibility(View.VISIBLE);
            isAddOrEdit = true;
            mTitleBarCommon.setRightTextViewString("");
        }else{
            mBookNameEdit.setText(mBook.bookName);
            isAddOrEdit = false;
        }

    }

    private class InitDataAsyncTask extends AsyncTask<Void,Void,Void> {

        private Book mBook;
        public InitDataAsyncTask(Book book) {
            mBook = book;
        }
        @Override
        protected Void doInBackground(Void... params) {

            if(!isAddOrEdit) {
                String para = new String("bookid="+mBook.bookid+"&bookName="+mBookNameEdit.getText().toString());
                String url = "http://139.199.89.89/api/v1/books";
                HttpUtil httpUtil = new HttpUtil();
                String response = httpUtil.post(BookDetail.this,url,para);
                Log.d(TAG,"<<<<<response="+response);
            }else{
                String para = new String("bookDescription="+mBookNameEdit.getText().toString()+"&bookName="+mBookNameEdit.getText().toString());
                String url = "http://139.199.89.89/api/v1/books";
                HttpUtil httpUtil = new HttpUtil();
                String response = httpUtil.post(BookDetail.this,url,para);
                Log.d(TAG,"<<<<<response="+response);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            finish();
        }
    }


    private void initTitle() {
        mTitleBarCommon = (TitleBarCommon)findViewById(R.id.head_common_layout);
        mTitleBarCommon.setRightTextViewString("删除");
        mTitleBarCommon.setRightTextViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isAddOrEdit) {
                    new DeleteAsyncTask().execute();
                }

            }
        });
        mTitleBarCommon.setLeftViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }


    private class DeleteAsyncTask extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... params) {
            String para = new String("bookid="+mBook.bookid);
            String url = "http://139.199.89.89/api/v1/books";
            HttpUtil httpUtil = new HttpUtil();
            httpUtil.doDelete(url,para);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            finish();
        }
    }
}

Http的操作是:

public void doDelete(String urlStr,String params){
    try{
        System.out.println(urlStr);
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("DELETE");
        DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
        conn.getOutputStream().write(params.getBytes());
        ds.flush();

        conn.getInputStream();
        if(conn.getResponseCode() ==200){
            System.out.println(">>>>>>成功");
        }else{
            System.out.println(conn.getResponseCode());
        }
    }catch (Exception ex) {
        ex.printStackTrace();
    }

}




public String post(Context context, final String strUrl, String params) {

    URL postUrl = null;
    try {
        postUrl = new URL(strUrl);
    } catch (MalformedURLException ex) {
        Log.e("HttpUtil", "get MalformedURL", ex);
        return null;
    }
    InputStream input = null;
    DataOutputStream ds = null;
    ByteArrayOutputStream byteOutStream = null;
    HttpURLConnection conn = null;
    byte[] outData = null;
    try {

        conn = getConnection(context, postUrl);
        connection = conn;
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(TIMEOUT * 2);
        conn.setReadTimeout(TIMEOUT * 2);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length",String.valueOf(params.getBytes().length));

        //byte[] data = new byte[BUF_LEN];
        ds = new DataOutputStream(conn.getOutputStream());

        conn.getOutputStream().write(params.getBytes());

        ds.flush();

        input = conn.getInputStream();


        byteOutStream = new ByteArrayOutputStream();

        outData = getResponse(input, byteOutStream, tmpBuf);

        if(mHandler != null){
            Message msg = new Message();
            msg.what = POST_PROGRESS_NOTIFY;
            msg.arg1 = 90;
            mHandler.sendMessage(msg);
        }

        String webcontent = null;
        if(outData != null && outData.length > 0){
            webcontent = new String(outData);
        }

        return webcontent;
    } catch (Exception ex) {
        Log.e("HttpUtil", "post", ex);
    } catch (OutOfMemoryError ex){
        Log.e("HttpUtil", "post OutOfMemoryError", ex);
    } finally {
        try {
            outData = null;
            if (input != null){
                input.close();
                input = null;
            }
            if (ds != null){
                ds.close();
                ds = null;
            }
            if (conn != null){
                conn.disconnect();
                conn = null;
            }
            if (byteOutStream != null){
                byteOutStream.close();
                byteOutStream = null;
            }
            if(mHandler != null){
                Message msg = new Message();
                msg.what = POST_PROGRESS_NOTIFY;
                msg.arg1 = 100;
                mHandler.sendMessage(msg);
            }
        } catch (Exception ex) {
            Log.e("HttpUtil", "post finally", ex);
        }
    }
    return null;
}

private byte[] getResponse(InputStream input, ByteArrayOutputStream byteOutStream, byte[] data) throws IOException {
    if(input == null || byteOutStream == null || data == null){
        return null;
    }
    int i = 0;
    while((i = input.read(data)) != -1){
        byteOutStream.write(data, 0, i);
    }

    byte[] bmpData = byteOutStream.toByteArray();
    return bmpData;
}

private HttpURLConnection getConnection(Context context, URL url) throws Exception{
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    return conn;
}

代码在https://github.com/nickgao1986/StepSport

0人推荐
随时随地看视频
慕课网APP