HttpUrlConnection的应用

一、什么是HttpUrlConnection

HttpUrlConnection是java的标准指定网站发送GET请求、post请求类、ttpUrlConnection继承自URLConnection,可用于向指定网站发送GET请求、post请求,httpUrlConnection在使用上相对简单,并且易于扩展,推荐使用。

 

二、如何使用HttpUrlCnnection

   1.创建URL对象。

   2.通过URL对象调用openConnection()方法获得HttpURLConnection对象。

   3.HttpURLConnection对象设置其它连接属性。

   4.HttpURLConnection对象调用getInputstream()方法下向服务器发送http请求并获取到服务器返回的输入流。

   5读取输入流,转换成String字符串。

 

三、使用HttpUrlConnection获取Http请求

public class MainActivity extends AppCompatActivity {

 
   private Button getwebBtn;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindID();
 
        getwebBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getWebInfo();
            }
        }).start();
    }
});
 
 
 
    }
 
    private void getWebInfo() {
 
        try {
                //找水源,创建URL
                URL url=new URL("http://mp.blog.csdn.net/postedit/79528472/");
                //开水闸-openConnection
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                //建水管-InputStream
                InputStream inputStream=httpURLConnection.getInputStream();
                //建蓄水池蓄水-InputStreamReader
                InputStreamReader reader=new InputStreamReader(inputStream,"UTF-8");
                //水桶盛水-BufferedReader
                BufferedReader bufferedReader=new BufferedReader(reader);
 
                StringBuffer stringBuffer= new StringBuffer();
                String temp=null;
 
                while ((temp=bufferedReader.readLine())!=null){
                    stringBuffer.append(temp);
                }
                bufferedReader.close();
                reader.close();
                inputStream.close();
 
                Log.e("MAIN",stringBuffer.toString());
 
 
 
 
            catch (MalformedURLException e) {
                e.printStackTrace();
            catch (IOException e) {
                e.printStackTrace();
            }
 
    }
 
 
    private void bindID() {
        getwebBtn=findViewById(R.id.getweb_btn);
    }
    class MyThread implements Runnable{
 
        @Override
        public void run() {
 
        }
}
 
Xml:
 
<Button
    android:text="点击进入"
    android:id="@+id/getweb_btn"
    android:layout_width="match_parent"
    android:layout_height="50dp" />
 

 

 

四、使用HttpURLConnection加载网络图片

加载网络图片,需要用到Bitmap对象。 
加载网络图片有时也需耗时较长时间,所以也应该异步加载。 

 

ImgActivity代码如下:

 

package lenovo.wangmengyuan.http;

 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
 
public class ImgActivity extends AppCompatActivity {
    private Button loadbt;
    private ImageView loadimg;
    private ProgressBar progressBar;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img);
        bindID();
        loadbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
         //       ImgloadTask task=new ImgloadTask(loadimg);
             //   task.execute("http://img5.imgtn.bdimg.com/it/u=717372819,1556613902&fm=27&gp=0.jpg");
                loadbt.setEnabled(false);
                 
 
            }
        });
    }
 
    private void bindID() {
        loadbt=findViewById(R.id.loadpig_bt);
        loadimg=findViewById(R.id.loadpig_img);
    }
}
 
XML:
 
<Button
    android:text="点击下载"
    android:id="@+id/loadpig_bt"
    android:layout_width="match_parent"
    android:layout_height="50dp" />
<ImageView
 
    android:scaleType="fitCenter"
    android:id="@+id/loadpig_img"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
 
ImgLoadTask:
 
package lenovo.wangmengyuan.http;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
/**
 * Created by Administrator on 2018/3/13.
 */
 
public class ImgloadTask extends AsyncTask<String,Integer,Bitmap> {
 
private ImageView imageView;
    //为什么要加一个构造方法-因为我们有传值的需求
    public  ImgloadTask(ImageView iv){
        this.imageView=iv;
    }
    @Override
    protected Bitmap doInBackground(String... strings) {
 
        Bitmap bm=null;
        try {
          URL  url = new URL(strings[0]);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            InputStream inputStream=connection.getInputStream();
            bm= BitmapFactory.decodeStream(inputStream);
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
 
        }
 
 
        //加载网络图片,最后获取到一个Bitmap对象,返回Bitmap对象
        return bm;
    }
 
    @Override
    protected void onPostExecute(Bitmap s) {
        super.onPostExecute(s);
        imageView.setImageBitmap(s);
    }
}
 

五、使用HttpURLConnection下载网络资源

ImgActivity.java代码:

 

package lenovo.wangmengyuan.http;

 
import android.Manifest;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
 
import com.master.permissionhelper.PermissionHelper;
 
import java.security.Permission;
 
public class ImgActivity extends AppCompatActivity {
    private Button loadbt;
    private ImageView loadimg;
    private ProgressBar progressBar;
    private String picUrl="http://http://pic3.nipic.com/20090623/2512829_165609054_2.jpg";
    private PermissionHelper permissionHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img);
        bindID();
      loadbt.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
 
permissionHelper=new PermissionHelper(ImgActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
       permissionHelper.request(new PermissionHelper.PermissionCallback() {
           @Override
           public void onPermissionGranted() {
               DownLoad2 task=new DownLoad2(ImgActivity.this,loadimg);
               task.execute(picUrl,"ghh.jpg");
 
           }
 
           @Override
           public void onIndividualPermissionGranted(String[] grantedPermission) {
 
           }
 
           @Override
           public void onPermissionDenied() {
 
           }
 
           @Override
           public void onPermissionDeniedBySystem() {
 
           }
       });
 
// new DownLoad2(ImgActivity.this,loadimg).execute(picUrl,"gff.jpg");
 
 
          }
      });
 
 
         //       ImgloadTask task=new ImgloadTask(loadimg);
             //   task.execute("http://img5.imgtn.bdimg.com/it/u=717372819,1556613902&fm=27&gp=0.jpg");
                //loadbt.setEnabled(false);
               // DownLoadTask dTask = new DownLoadTask(ImgActivity.this,loadbt,progressBar);
               // dTask.execute("http://img1.bitautoimg.com/bitauto/2012/09/17/a50cdcf8-1a2a-418b-b7be-d81f36ab12ee.jpg\",\"fra.jpg");
 
 
 
            }
 
    private void bindID() {
        loadbt=findViewById(R.id.loadpig_bt);
        loadimg=findViewById(R.id.loadpig_img);
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionHelper!=null){
            permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
 
DownLoad2代码如下
 
public class DownLoad2 extends AsyncTask<String,Integer,Integer> {
 
 
    private String dirPath;//下载目录的途径
    private String filePath;//文件储存位置,列入
    private ImageView loading;
    private Context context;
    public   DownLoad2(Context context,ImageView loading){
    this.context=context;
     this.loading=loading;
}
 
    InputStream inputStream=null;
    OutputStream o =null;
    @Override
    protected Integer doInBackground(String... strings) {
        String fileName=strings[1];//存储图片的名字
        //判断目录是否存在,不存在,创建目录
        dirPath= Environment.getExternalStorageDirectory() + "/"+"http_download/";
        File dir=new File(dirPath);//创建文件对象
        if (dir.exists()){
            dir.mkdir();
        }
//判断文件是否存在,不存在创建
        filePath=dirPath+fileName;
        File file=new File(filePath);
        if (file.exists()){
            return -1;
 
        }
        else {
            try {
                file.createNewFile();//不存在创建新的
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        InputStream inputStream=null;
        FileOutputStream outputStream=null;
 
 
        URL url= null;
        try {
            url = new URL(strings[0]);
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode()==200){
                //判断返回码是否正常,若
                inputStream=connection.getInputStream();
            }
            else {
                return -2;
            }
            outputStream=new FileOutputStream(file);
            int length=0;
            byte[] buffer=new byte[4*1024];
            while ((length=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,length);
 
 
            }
            outputStream.close();
            inputStream.close();
 
 
 
        catch (IOException e) {
            e.printStackTrace();
        }
 
        return 1;
    }
 
    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        switch (integer){
            case 1:
                //正常下载完成
                Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT).show();
                Bitmap bm= BitmapFactory.decodeFile(filePath);
                loading.setImageBitmap(bm);
                break;
            case -1:
                //文件已存在
                Toast.makeText(context,"文件已存在",Toast.LENGTH_SHORT).show();
                break;
            case -2:
                //网络异常
                Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                break;
        }
    }
 
外加文件读取权限以及网络请求权限:

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

posted @ 2020-03-26 15:20  journey_IT  阅读(229)  评论(0编辑  收藏  举报