判断HttpURLConnection与HttpClient请求

来源:互联网 发布:hp1022n网络打印驱动 编辑:程序博客网 时间:2024/06/16 12:03

1、权限

网络请求权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
网络判断权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
2、使用HttpClien请求是一种过时的方法需在Gradle中Android{
useLibrary 'org.apache.http.legacy'
}
3、布局
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.chenweifei20171104.MainActivity">    <RadioGroup        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:orientation="horizontal"        android:id="@+id/rg">        <RadioButton            android:layout_weight="1"            android:id="@+id/rb0"            android:button="@null"            android:gravity="center"            android:text="首页"            android:checked="true"            android:background="@drawable/radiobutton_selector"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <RadioButton            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="@drawable/radiobutton_selector"            android:layout_weight="1"            android:button="@null"            android:gravity="center"            android:text="发现"            android:id="@+id/rb1"/>        <RadioButton            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="@drawable/radiobutton_selector"            android:layout_weight="1"            android:button="@null"            android:gravity="center"            android:text="下载"            android:id="@+id/rb2"/>    </RadioGroup>    <FrameLayout        android:id="@+id/fl"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_above="@+id/rg"></FrameLayout></RelativeLayout>

fragment1
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ListView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/lv"></ListView></LinearLayout>

fragment2
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ListView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/lv"></ListView></LinearLayout>

item布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:padding="10dp"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ImageView        android:id="@+id/image_view"        android:layout_width="100dp"        android:layout_height="100dp" />    <TextView        android:id="@+id/text_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

Drawable
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <!--选中时是红色-->    <item android:state_checked="true" android:drawable="@android:color/holo_red_dark"></item>    <item android:drawable="@android:color/white"></item></selector>

代码
main
package com.example.chenweifei20171104;import android.support.annotation.IdRes;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.RadioGroup;import com.example.chenweifei20171104.Fragment.Fxain;import com.example.chenweifei20171104.Fragment.Shouye;import com.example.chenweifei20171104.Fragment.Xiazai;import com.example.chenweifei20171104.Utils.NetStateUtil;public class MainActivity extends AppCompatActivity {    private RadioGroup rg;    private Shouye shouye;    public Xiazai xiazai;    public Fxain fxain;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //判断网络是否连接        boolean conn = NetStateUtil.isConn(this);        if (!conn){            NetStateUtil.showNoNetWorkDlg(this);        }        //获取控件        rg=(RadioGroup)findViewById(R.id.rg);        //创建Shouye对象        shouye = new Shouye();        //开启事务        getSupportFragmentManager().beginTransaction().add(R.id.fl,shouye).commit();        //设置监听        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {                //隐藏所有Fragment;                hideFragments();                switch (checkedId) {                    case R.id.rb0:                        getSupportFragmentManager().beginTransaction().show(shouye).commit();                        break;                    case R.id.rb1:                        if (fxain == null) {                            fxain = new Fxain();                            getSupportFragmentManager().beginTransaction().add(R.id.fl, fxain).commit();                        } else {                            getSupportFragmentManager().beginTransaction().show(fxain).commit();                        }                        break;                    case R.id.rb2:                        if (xiazai == null) {                            xiazai = new Xiazai();                            getSupportFragmentManager().beginTransaction().add(R.id.fl, xiazai).commit();                        } else {                            getSupportFragmentManager().beginTransaction().show(xiazai).commit();                        }                        break;                }            }        });    }    private void hideFragments(){        if(shouye!=null&&shouye.isAdded()){            getSupportFragmentManager().beginTransaction().hide(shouye).commit();        }        if(fxain!=null&&fxain.isAdded()){            getSupportFragmentManager().beginTransaction().hide(fxain).commit();        }        if(xiazai!=null&&xiazai.isAdded()){            getSupportFragmentManager().beginTransaction().hide(xiazai).commit();        }    }}

fragment1
package com.example.chenweifei20171104.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import com.example.chenweifei20171104.Bean.Result;import com.example.chenweifei20171104.R;import com.example.chenweifei20171104.Utils.ImageloaderUtil;import com.example.chenweifei20171104.Utils.MyTask;import com.google.gson.Gson;import com.nostra13.universalimageloader.core.ImageLoader;import java.util.List;/** * Created by DELL on 2017/11/4. */public class Fxain extends Fragment {    private ListView lv;    private List<Result.NewslistBean> list;    private  MyAdapterss myAdapter;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.s_f1, null);        //获取控件        lv=(ListView)view.findViewById(R.id.lv);        //异步请求数据        MyTask myTask = new MyTask(new MyTask.Icallbacks() {            @Override            public void updataUiByjson(String jsonstr) {                //创建Gson                Gson gson = new Gson();                Result result = gson.fromJson(jsonstr, Result.class);                //得到集合                list = result.getNewslist();                //设置适配器                setAdapter();            }        });        myTask.execute(new String[]{"http://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10", "1"});        return view;    }    private void setAdapter() {        if(myAdapter==null){            //设置适配器            myAdapter = new MyAdapterss();            lv.setAdapter(myAdapter);        }else{            myAdapter.notifyDataSetChanged();        }    }    class MyAdapterss extends BaseAdapter {        @Override        public int getCount() {            return list.size();        }        @Override        public Object getItem(int position) {            return list.get(position);        }        @Override        public long getItemId(int position) {            return position;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {            ViewHolder vh;            if (convertView==null){                vh = new ViewHolder();                convertView=View.inflate(getActivity(), R.layout.item_layout,null);                vh.img=(ImageView)convertView.findViewById(R.id.image_view);                vh.tv=(TextView)convertView.findViewById(R.id.text_title);                convertView.setTag(vh);            }else{                vh= (ViewHolder) convertView.getTag();            }            //设置            vh.tv.setText(list.get(position).getTitle());            ImageLoader.getInstance().displayImage(list.get(position).getPicUrl(),vh.img, ImageloaderUtil.getImageOptions());            return convertView;        }        class ViewHolder{            private ImageView img;            private TextView tv;        }    }}

fragment2
package com.example.chenweifei20171104.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import com.example.chenweifei20171104.Bean.Result;import com.example.chenweifei20171104.R;import com.example.chenweifei20171104.Utils.ImageloaderUtil;import com.example.chenweifei20171104.Utils.MyTask;import com.google.gson.Gson;import com.nostra13.universalimageloader.core.ImageLoader;import java.util.List;/** * Created by DELL on 2017/11/4. */public class Shouye extends Fragment {    private List<Result.NewslistBean> list;    private ListView lv;    private MyAdapterss myAdapter;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container            , @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.s_f2, null);        //获取控件        lv=(ListView)view.findViewById(R.id.lv);        //异步请求数据        MyTask myTask = new MyTask(new MyTask.Icallbacks() {            @Override            public void updataUiByjson(String jsonstr) {                //创建Gson                Gson gson = new Gson();                Result result = gson.fromJson(jsonstr, Result.class);                //得到集合                  list = result.getNewslist();                //设置适配器                setAdapter();            }        });        myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10", "2"});        return view;    }    private void setAdapter() {        if(myAdapter==null){            //设置适配器            myAdapter = new MyAdapterss();            lv.setAdapter(myAdapter);        }else{            myAdapter.notifyDataSetChanged();        }    }    class MyAdapterss extends BaseAdapter {        @Override        public int getCount() {            return list.size();        }        @Override        public Object getItem(int position) {            return list.get(position);        }        @Override        public long getItemId(int position) {            return position;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {            ViewHolder vh;            if (convertView==null){                vh = new ViewHolder();                convertView=View.inflate(getActivity(), R.layout.item_layout,null);                vh.img=(ImageView)convertView.findViewById(R.id.image_view);                vh.tv=(TextView)convertView.findViewById(R.id.text_title);                convertView.setTag(vh);            }else{                vh= (ViewHolder) convertView.getTag();            }            //设置            vh.tv.setText(list.get(position).getTitle());            ImageLoader.getInstance().displayImage(list.get(position).getPicUrl(),vh.img, ImageloaderUtil.getImageOptions());            return convertView;        }        class ViewHolder{            private ImageView img;            private TextView tv;        }    }}

Utils
package com.example.chenweifei20171104.Utils;import android.content.Context;import android.graphics.Bitmap;import android.os.Environment;import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;import java.io.File;/** * Created by DELL on 2017/10/17. */public class ImageloaderUtil {    public static void initConfig(Context context) {        //配置//        File cacheFile=context.getExternalCacheDir();        File cacheFile= new File(Environment.getExternalStorageDirectory()+"/"+"image");        ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(context)                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽                .threadPoolSize(2)//线程池的数量                .threadPriority(4)                .memoryCacheSize(2*1024*1024)//设置内存缓存区大小                .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小                .diskCache(new UnlimitedDiscCache(cacheFile))//自定义缓存目录                .writeDebugLogs()//打印日志内容                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理                .build();        ImageLoader.getInstance().init(config);    }    /**     * 获取图片设置类     * @return     */    public static DisplayImageOptions getImageOptions(){        DisplayImageOptions optionsoptions=new DisplayImageOptions.Builder()                .cacheInMemory(true)//使用内存缓存                .cacheOnDisk(true)//使用磁盘缓存                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片格式                .displayer(new RoundedBitmapDisplayer(10))//设置圆角,参数代表弧度                .build();        return optionsoptions;    }}

package com.example.chenweifei20171104.Utils;import android.app.Application;/** * Created by DELL on 2017/10/20. */public class MyApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        ImageloaderUtil.initConfig(this);    }}

package com.example.chenweifei20171104.Utils;import android.os.AsyncTask;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ssl.AllowAllHostnameVerifier;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by DELL on 2017/10/17. */public class MyTask extends AsyncTask<String,Void,String> {    //申请一个接口类对象    private Icallbacks icallbacks;    //将无参构造设置成私有的,使之在外部不能够调用    private MyTask() {    }    //定义有参构造方法    public MyTask(Icallbacks icallbacks) {        this.icallbacks = icallbacks;    }    @Override    protected String doInBackground(String... params) {          String str="";        //得到请求的类型        String type = params[1];        if ("1".equals(type)) {//如果是"1" 执行 HttpGet请求            //获取httpclient对象            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();            //准备一个get请求//        HttpGet httpGet = new HttpGet(jsonUrl);            HttpPost httpPost = new HttpPost(params[0]);            try {                //得到服务器返回的数据;                HttpResponse response = defaultHttpClient.execute(httpPost);                //得到状态码                int statusCode = response.getStatusLine().getStatusCode();                if(statusCode ==200){                    //entiry 里面封装的数据;                    HttpEntity entity = response.getEntity();                    str = EntityUtils.toString(entity);                }            } catch (IOException e) {                e.printStackTrace();            }        } else if ("2".equals(type)) {//如果是2执行 HttpUrlConnection请求            try {                //1.创建Url对象                URL url = new URL(params[0]);                //2.打开连接                HttpURLConnection connection = (HttpURLConnection) url.openConnection();                //3.设置                connection.setRequestMethod("GET");                connection.setConnectTimeout(5000);                connection.setReadTimeout(5000);                //4.得到响应码,进行判断                int code = connection.getResponseCode();                if (code == 200) {                    //5.得到结果                    InputStream inputStream = connection.getInputStream();                    //调用工具类中的静态方法                    str=StreamToString.streamTostr(inputStream,"utf-8");                }            } catch (Exception ex) {                ex.printStackTrace();            }        } else {        }        return str;    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        //解析,封装到bean,更新UI组件        icallbacks.updataUiByjson(s);    }    //定义一个接口    public  interface Icallbacks{        //根据回传的json字符串,解析并更新页面组件            void updataUiByjson(String jsonstr);        }}

package com.example.chenweifei20171104.Utils;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import com.example.chenweifei20171104.R;/** * 得到网络状态的工具类 * Created by e531 on 2017/10/16. */public class NetStateUtil {    /* * 判断网络连接是否已开 * true 已打开  false 未打开 * */    public static boolean isConn(Context context){        boolean bisConnFlag=false;        ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo network = conManager.getActiveNetworkInfo();        if(network!=null){            bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();        }        return bisConnFlag;    }    /**     * 当判断当前手机没有网络时选择是否打开网络设置     * @param context     */    public static void showNoNetWorkDlg(final Context context) {        AlertDialog.Builder builder = new AlertDialog.Builder(context);        builder.setIcon(R.mipmap.ic_launcher)         //                .setTitle(R.string.app_name)            //                .setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                // 跳转到系统的网络设置界面                Intent intent = null;                // 先判断当前系统版本                if(android.os.Build.VERSION.SDK_INT > 10){  // 3.0以上                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);                }else{                    intent = new Intent();                    intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");                }                context.startActivity(intent);            }        }).setNegativeButton("知道了", null).show();    }}

package com.example.chenweifei20171104.Utils;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * Created by DELL on 2017/10/17. */public class StreamToString {    public static String streamTostr(InputStream inputStream, String chartSet){        StringBuilder builder = new StringBuilder();        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));        String con;        try {            while((con=reader.readLine())!=null){                StringBuilder append = builder.append(con);            }            return builder.toString();        } catch (IOException e) {            e.printStackTrace();        }        return "";    }}

原创粉丝点击