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实现
流程图
好吧,我的流程图(独一无二,这么丑的图片也当得起这个称呼了!!!),绘了好久,对照一下我在网上找的流程图
标签:URLConnection,http,String,java,connection,result,import,Http,流程图 来源: https://blog.csdn.net/foshengtang/article/details/111355559