HttpUrlConnection

什么是Http请求

Http请求是被客户端和服务器端之间,发送请求和返回应答的标准

什么是HttpUrlConnection

HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。虽然HttpURLConnection的API提供的比较简单,但是同时这也使得我们可以更加容易地去使用和扩展它。

如何使用HttpUrlConnection

1.创建URL对象。
2.通过URL对象调用openConnection()方法获得HttpURLConnection对象。
3.HttpURLConnection对象设置其它连接属性。
4.HttpURLConnection对象调用getInputstream()方法下向服务器发送http请求并获取到服务器返回的输入流。
5读取输入流,转换成String字符串。

使用如何使用HttpUrlConnection获取Http请求


public class MainActivity extends AppCompatActivity {

    private Button button;

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


        bindID();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getWebInfo();
                    }
                }).start();
            }
        });


    }

    private void getWebInfo() {

        try {
            //1.寻找水源--创建URL
            URL url =new URL("https://www.youkuaiyun.com/");
            //2.开水闸--openConnection
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            //3.建管道--InputStream
            InputStream inputStream=httpURLConnection.getInputStream();
            //4.建水池--InputStreamReader
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"UTF-8");
            //5.水桶盛水--BufferedReader
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);

            StringBuffer stringBuffer=new StringBuffer();
            String temp=null;

            while ((temp=bufferedReader.readLine())!=null){
                stringBuffer.append(temp);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

            Log.e("MAIN",stringBuffer.toString());


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void bindID() {
        button=findViewById(R.id.getweb_btn);
    }

HttpUrlConnection下载图片

MainActicity中的代码


    private ProgressBar progressBar;
    private Button button;
    private ImageView imageView;

    private String pic="http://p.yjbys.com/image/20170301/1488351756222990.png";

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

        bindID();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Down down =new Down(Main4Activity.this,imageView);
                down.execute(pic,"pi1.jip");
            }
        });
    }

    private void bindID() {

        imageView=findViewById(R.id.down_iv);
        button=findViewById(R.id.down_btn);

    }

down中的代码


public class Down extends AsyncTask<String,Integer,Integer> {




    private String dirPATH;//下载图片的目录
    private String filePATH;//文件具体的储存位置
    private ImageView imageView;
    private Context context;

    public Down(Context context, ImageView imageView){
        this.context=context;
        this.imageView=imageView;

    }

    @Override
    protected Integer doInBackground(String... strings) {

        String fileName =strings[1];//要储存的图片名字


        //判断目录是否存在,若不存在,创建目录
        dirPATH= Environment.getExternalStorageDirectory()+"/pic/";


        File dir=new File(dirPATH);//目录对象
        if (!dir.exists()){
            dir.mkdirs();
        }

        //判断文件是否存在,若不存在,创建文件
        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;
        OutputStream outputStream=null;

        try {
            URL url=new URL(strings[0]);
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            if (httpURLConnection.getResponseCode()==200){
                inputStream=httpURLConnection.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 (MalformedURLException e) {
            e.printStackTrace();
        } 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 bitmap= BitmapFactory.decodeFile(filePATH);
                imageView.setImageBitmap(bitmap);
                break;
            case -1:
                //文件已存在
                Toast.makeText(context,"文件已存在",Toast.LENGTH_SHORT).show();
                break;
            case -2:
                //网络异常
                Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
### Java 中 `HttpURLConnection` 的使用方法 #### 1. 基本概念 `HttpURLConnection` 是 Java 提供的一个用于执行 HTTP 请求的类。它允许开发者通过 URL 对象建立连接并发送 GET、POST 等类型的请求[^3]。 #### 2. 创建连接 要创建一个基于 `HttpURLConnection` 的 HTTP 连接,通常需要以下几个步骤: - 将目标地址封装成 `URL` 对象。 - 调用 `openConnection()` 方法获取到 `HttpURLConnection` 实例。 以下是基本代码示例: ```java import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws Exception { String urlString = "http://example.com"; URL url = new URL(urlString); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 设置请求方式 int responseCode = conn.getResponseCode(); // 获取响应码 System.out.println("Response Code: " + responseCode); conn.disconnect(); // 断开连接 } } ``` 上述代码展示了如何打开一个简单的 HTTP GET 请求,并打印服务器返回的状态码[^1]。 #### 3. 发送 POST 请求 如果需要向服务器提交数据,则可以设置请求头以及写入请求体的内容。下面是一个完整的 POST 请求示例: ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { public static void main(String[] args) throws Exception { String urlString = "http://example.com/api"; URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); // 启用输出流 conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); try(OutputStream os = conn.getOutputStream()) { // 写入 JSON 数据 byte[] input = "{\"key\":\"value\"}".getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = conn.getResponseCode(); System.out.println("Post Response Code : " + responseCode); conn.disconnect(); } } ``` 此代码片段演示了如何构建带有 JSON 数据的 POST 请求。 #### 4. 处理常见问题 ##### (1)超时设置 为了避免因网络延迟而导致程序卡住的情况,可以通过以下两个参数来设定读取和连接的时间限制: ```java conn.setConnectTimeout(5000); // 单位毫秒 conn.setReadTimeout(5000); ``` ##### (2)Android 版本兼容性 对于 Android 平台而言,在版本 2.3 及以上推荐优先选用 `HttpURLConnection` 替代已废弃的 `Apache HttpClient` 库[^2]。 ##### (3)重定向处理 默认情况下,`HttpURLConnection` 不会自动跟随 HTTP 重定向(状态码 3xx)。若希望支持该功能,需手动启用: ```java conn.setInstanceFollowRedirects(true); ``` #### 总结 综上所述,`HttpURLConnection` 是一种强大而灵活的方式来进行 HTTP 操作。尽管其配置过程可能稍显复杂,但它提供了足够的控制力去满足大多数应用场景的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值