android--(http协议、显示网络中的图片、https)

https:
android httpClient 支持HTTPS的访问方式 - http://mobile.51cto.com/aprogram-447714.htm

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

public class MainActivity extends AppCompatActivity {

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


    public void checkNet(View view) {
        boolean newWork = isNetworkConnected(this);

        boolean wifi = isWiffiConnected(this);

        boolean mobile = isMobileConnected(this);

       int t =  getConnectedType(this);

        if (newWork) {
            Toast.makeText(this, "网络可用", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "网络不可用", Toast.LENGTH_SHORT).show();
        }

        if (wifi) {
            Toast.makeText(this, "wifi可用", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "wifi不可用", Toast.LENGTH_SHORT).show();
        }


        if (mobile) {
            Toast.makeText(this, "mobile可用", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "mobile不可用", Toast.LENGTH_SHORT).show();
        }


        Toast.makeText(this, "网络类型:"+t, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断网络是否可用
     *
     * @param context
     * @return
     */
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断 wifi 是否可用
     *
     * @param context
     * @return
     */
    public boolean isWiffiConnected(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);

            //根据网络的类型,获取相就类型的网络信息
            NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (wifi != null) {
                return wifi.isAvailable();
            }
        }
        return false;
    }


    /**
     * 判断 Mobile 网络是不可用
     *
     * @param context
     * @return
     */
    public boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobileNet = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (mobileNet != null) {
                return mobileNet.isAvailable();
            }
        }

        return false;
    }


    /**
     * 获取当前网络链接的类型信息
     *
     * @param context
     * @return
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isAvailable()) {
                return networkInfo.getType();
            }
        }

        return -1;
    }


}

这里写图片描述

这里写图片描述

/**
 * 访问的网络必须在 线程中完成,显示网络中的图片
 */
public class Img extends AppCompatActivity {

    private static ImageView imageView;
    private final MyHandler myHandler = new MyHandler(this);
    private static final int LOAD_SUCESS = 0x1;

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

        imageView = (ImageView) findViewById(R.id.imageView);

        showImg();
    }


    /**
     * 线程之间进行通信处理
     */
    private static class MyHandler extends Handler {

        //软引用对象
        private final WeakReference<Img> weakReference;

        public MyHandler(Img img) {
            this.weakReference = new WeakReference<Img>(img);
        }

        @Override
        public void handleMessage(Message msg) {
            Img img = weakReference.get();
            if (img != null) {
                switch (msg.what) {
                    case LOAD_SUCESS:
                        // 在图片视图中显示 图片
                        imageView.setImageBitmap((Bitmap) msg.obj);
                        break;
                }
            }
        }
    }

    /**
     * 网络显示图片 需要在线程中进行,防止网络阻塞
     */
    public void showImg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "http://img2.imgtn.bdimg.com/it/u=2655910209,3235656411&fm=21&gp=0.jpg";
                try {
                    URL url = new URL(path);
                    InputStream in = url.openStream();

                    //以什么形式解码
                    Bitmap bitmap = BitmapFactory.decodeStream(in);

                    //数据存入 handler的message
                    Message message = myHandler.obtainMessage(LOAD_SUCESS, bitmap);

                    //发送
                    myHandler.sendMessage(message);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

}

activity.xml
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Img"
            android:label="@string/title_activity_img" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

这里写图片描述

public class HttpUrl extends AppCompatActivity {


    private TextView tv_info;
    private EditText et_username, et_password;

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

        tv_info = (TextView) findViewById(R.id.tv_info);
        et_username = (EditText) findViewById(R.id.editText_username);
        et_password = (EditText) findViewById(R.id.editText_password);
    }

    public void logIn(View view) {
        String username = et_username.getText().toString();

        String password = et_password.getText().toString();

        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }


        new Thread(new Runnable() {
            @Override
            public void run() {

                //这个路径为本地的 web服务器应用路径
                String path = "http://10.0.2.2:8080/";
                try {
                    URL url = new URL(path);

                    //建立http链接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    //请求方式
                    conn.setRequestMethod("POST");

                    //因为是post请求
                    conn.setDoOutput(true);

                    //因为是HttpURLConnection
                    conn.setDoInput(true);

                    //链接超时 时间毫秒
                    conn.setConnectTimeout(1000 * 30);

                    //数据超时
                    conn.setReadTimeout(1000 * 30);

                    //不缓存
                    conn.setUseCaches(false);

                    //请求的属性
                    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

                    //对服务器端读取或写入数据(使用输入输出流)

                    //获取链接的输出流
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());

                    //往服务端写入参数数据
                    out.writeBytes("username=" + URLEncoder.encode(et_username.getText().toString(), "gbk"));

                    out.writeBytes("&password=" + URLEncoder.encode(et_password.getText().toString(), "gbk"));

                    out.flush();
                    out.close();


                    /***********从服务端获取数据***********************/
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));//字节流转字符流

                    String result = br.readLine();

                    br.close();

                    conn.disconnect();//关闭http链接

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


            }
        }).start();


    }

}

这里写图片描述

这里写图片描述

//先将参数放入List,再对参数进行URL编码  
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();  
params.add(new BasicNameValuePair("param1", "中国"));  
params.add(new BasicNameValuePair("param2", "value2"));  

//对参数编码  
String param = URLEncodedUtils.format(params, "UTF-8");  

//baseUrl             
String baseUrl = "http://ubs.free4lab.com/php/method.php";  

//将URL与参数拼接  
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);  

HttpClient httpClient = new DefaultHttpClient();  

try {  
    HttpResponse response = httpClient.execute(getMethod); //发起GET请求  

    Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码  
    Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容  
} catch (ClientProtocolException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}  

这里写图片描述

/和GET方式一样,先将参数放入List  
params = new LinkedList<BasicNameValuePair>();  
params.add(new BasicNameValuePair("param1", "Post方法"));  
params.add(new BasicNameValuePair("param2", "第二个参数"));  

try {  
    HttpPost postMethod = new HttpPost(baseUrl);  
    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中  

    HttpResponse response = httpClient.execute(postMethod); //执行POST方法  
    Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码  
    Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容  

} catch (UnsupportedEncodingException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (ClientProtocolException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
} catch (IOException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
}  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值