您的位置:首页 > 理论基础 > 计算机网络

httpUrlConnection

2017-08-06 19:35 113 查看
public class MainActivity extends AppCompatActivity {

    private ListView listView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.mylist);

        findViewById(R.id.mybtn).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

                NetworkInfo info = manager.getActiveNetworkInfo();

                if (info != null && info.isAvailable()) {//网络可用

                    MyTask task = new MyTask();

                    try {

                        String path = "http://apis.juhe.cn/cook/query.php";

                        String value = "menu=" + URLEncoder.encode("土豆", "utf-8") + "&key=13af589c334ec80c037688e927407966&rn=1";

                       //开启异步任务,传入一个string数组,第一个是网络地址,第二个是参数;

                        task.execute(new String[]{path, value});

                    } catch (UnsupportedEncodingException e) {

                        e.printStackTrace();

                    }

                } else {

                    //弹出提醒网络未开启,跳转开启网络界面

                    showDialog();

                }

            }

        });

    }

    //重写异步任务

    class MyTask extends AsyncTask<String, Integer, DataBean> {

        @Override

        protected DataBean doInBackground(String... params) {

            //网络请求

            String json = getNetData(params[0], params[1]);

            DataBean bean = new Gson().fromJson(json, DataBean.class);

            return bean;

        }

        @Override

        protected void onPostExecute(DataBean dataBean) {

            super.onPostExecute(dataBean);

            //UI操作,给listview赋值,显示第一个菜单里的步骤

            MyAdapter adapter = new MyAdapter(MainActivity.this, dataBean.result.data.get(0).steps);

            listView.setAdapter(adapter);

        }

    }

    //post网络请求

    private String getNetData(String path, String value) {

        //获取URL的对象

        try {

            URL url = new URL(path);

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

            connection.setRequestMethod("POST");

            connection.setDoOutput(true);

            //写入参数

            OutputStream outputStream = connection.getOutputStream();

            outputStream.write(value.getBytes());

            //获取网络请求状态码

            int code = connection.getResponseCode();

            //200,连接成功

            System.out.println(code+"  code");

            if (code == HttpURLConnection.HTTP_OK) {

                //获取网络请求返回的输入流

                InputStream is = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                String str = "";

                StringBuilder builder = new StringBuilder();

                while ((str = reader.readLine()) != null) {

                    builder.append(str);

                }

                return builder.toString();

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    //显示网络提醒对话框

    private void showDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("网络状态提醒");

        builder.setMessage("您的网络未开启,是否开启网络?");

        builder.setPositiveButton("开启网络", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                //开启网络界面,使用隐示意图

                //根据版本号做不同操作

                if (Build.VERSION.SDK_INT > 10) {

                    Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);

                    startActivity(intent);

                } else {

                    //SDK<10

                    Intent intent = new Intent();

                    ComponentName name = new ComponentName("com.android.settings", "com.android.settings.WIRELESS_SETTINGS");

                    // Settings.ACTION_WIRELESS_SETTINGS;

                    intent.setComponent(name);

                    intent.setAction(Intent.ACTION_VIEW);

                    startActivity(intent);

                }

                dialog.dismiss();

            }

        });

        builder.setNegativeButton("不开启", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }

        });

        builder.create().show();

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  httpUrlConnection