http(S)系列之(五):android之Http(s)URLConnection(6):流程图

前言

讲个题外话:大概小学四年级,老师会讲解写作文要有大纲,可惜,自始至终都没有认真对待这件事情。现在认真对待我相信应该不算晚,不只是写文章,做所有的事情都应该有大纲,这样不会在过程中手忙脚乱。

demo

package com.fosheng.originaltec.urlconnection;

import org.junit.Test;

/**
 * Copyright (C), 2019-2020, 佛生
 * FileName: InterfaceUtilTest
 * Author: 佛学徒
 * Date: 2020/12/2 10:08
 * Description:
 * History:
 */
public class InterfaceUtilTest {

    @Test
    public void testURLConnection() {
        String result = InterfaceUtil.gethttp("https://www.baidu.com/");
        System.out.println("輸出結果:" + result);
    }
}
package com.fosheng.originaltec.urlconnection;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Copyright (C), 2019-2020, 佛生
 * FileName: InterfaceUtil
 * Author: 佛学徒
 * Date: 2020/12/2 9:48
 * Description: 調用網絡請求接口,測試post
 * History:
 */
public class InterfaceUtil {

    public static String gethttp(String urlStr) {
        String result;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            //得到connection对象。
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //连接
            connection.connect();
            //得到响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到响应流
                InputStream inputStream = connection.getInputStream();
                //将响应流转换成字符串
                result = is2String(inputStream);//将流转换为字符串。
            } else {
                result = "當前狀態信息:" + responseCode;
            }

        } catch (Exception e) {
            e.printStackTrace();
            result = e.getMessage();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return result;
    }

    private static String is2String(InputStream inputStream) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String str = result.toString(StandardCharsets.UTF_8.name());
        return str;
    }
}

代码先贴出来,流程图就是按照该demo实现

流程图

在这里插入图片描述
好吧,我的流程图(独一无二,这么丑的图片也当得起这个称呼了!!!),绘了好久,对照一下我在网上找的流程图
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值