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

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

标签:
Android

后台使用php中thinkphp来写,可以参考:https://www.imooc.com/article/267425

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

在安卓中我们使用HttpURLConnection来进行请求

我们看主activity的代码:

public class TestHttpActivity extends Activity implements AdapterView.OnItemClickListener {

    public static final String TAG = TestHttpActivity.class.getSimpleName();
    private ArrayList<Book> mBookArrayList;
    private BookMainAdapter mBookMainAdapter;

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context,TestHttpActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feeds_main);

        initTitle();
        ListView listView = (ListView) findViewById(R.id.news_home_listview);
        mBookMainAdapter = new BookMainAdapter(this);
        listView.setAdapter(mBookMainAdapter);
        listView.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        new InitDataAsyncTask().execute();

    }

    private void initTitle() {
        TitleBarCommon titleBarCommon = (TitleBarCommon)findViewById(R.id.head_common_layout);
        titleBarCommon.setRightTextViewString("增加");
        titleBarCommon.setRightTextViewListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BookDetail.startActivity(TestHttpActivity.this,null);

            }
        });
    }

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

        @Override
        protected Void doInBackground(Void... params) {
            HttpUtil httpUtil = new HttpUtil();
            String url = "http://139.199.89.89/api/v1/books";
            String response = httpUtil.get(TestHttpActivity.this,url);
            Log.d(TAG,"response="+response);
            parseResponse(response);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.d(TAG,"<<<<<mBookArrayList="+ mBookArrayList);
            mBookMainAdapter.setList(mBookArrayList);
        }
    }

    private void parseResponse(String response) {
        try{
            Gson gson = new Gson();
            JSONArray jsonArray = new JSONArray(response);
            ArrayList<Book> books;
            mBookArrayList = new Gson().fromJson(response, new TypeToken<List<Book>>(){}.getType());

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Book book = mBookArrayList.get(position);
        BookDetail.startActivity(TestHttpActivity.this,book);
    }
}

注意所有的网络请求都要放到子线程中,不然会报错

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:background="@color/white_a"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="vertical">

    <com.pic.optimize.view.TitleBarCommon
        android:id="@+id/head_common_layout"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="@color/red_bn"
        android:gravity="center_vertical"/>

    <ListView
        android:id="@+id/news_home_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@null"
        android:fadingEdge="none"
        android:footerDividersEnabled="true"
        android:listSelector="@color/trans_color"
        android:scrollbars="none"
        android:scrollingCache="false" />

</LinearLayout>

看Get操作:

public String get(Context context, final String strUrl) {
    URL getUrl = null;

    try {
        getUrl = new URL(strUrl);
    } catch (MalformedURLException ex) {
        Log.e("HttpUtil", "get MalformedURL", ex);
        return null;
    }
    InputStream input = null;
    ByteArrayOutputStream byteOutStream = null;
    HttpURLConnection conn = null;
    byte[] outData = null;
    try {
        conn = getConnection(context, getUrl);
        connection = conn;
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setDoInput(true);


        conn.connect();

        input = conn.getInputStream();

        String webcontent = null;

        byteOutStream = new ByteArrayOutputStream();
        //byte[] buf = new byte[BUF_LEN];
        int i = 0;
        while((i = input.read(tmpBuf)) != -1){
            byteOutStream.write(tmpBuf, 0, i);
        }

        outData = byteOutStream.toByteArray();
        if(outData != null && outData.length > 0){
            webcontent = new String(outData);
        }
        return webcontent;
    } catch (Exception ex) {
        Log.e("HttpUtil", "get", ex);
        //return ex.getMessage();
    } finally {
        try{
            outData = null;
            if(input != null){
                input.close();
                input = null;
            }

            if(byteOutStream != null){
                byteOutStream.close();
                byteOutStream = null;
            }
            if(conn != null){
                conn.disconnect();
                conn = null;
            }
        } catch(Exception ex){
            Log.e("HttpUtil", "get finally", ex);
            //return ex.getMessage();
        }

    }

    return null;
}

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

点击查看更多内容
TA 点赞

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

评论

作者其他优质文章

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

100积分直接送

付费专栏免费学

大额优惠券免费领

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

举报

0/150
提交
取消