为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Android

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

https://img1.sycdn.imooc.com//5c12283e0001708b06461124.jpg


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

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消