懒得说了,下面是工具类代码,自己看吧,可以发Get,Post请求和加载网络图片
package com.example.book3.Test;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
* Android 网络请求的方法
* android的网络请求通常需要在子线程中完成,通过Handler回调接受请求结果并在主线程中根据结果进行操作
*/
public class HttpUtils {
// 定义一个获取网络图片数据的方法:
public static void getImage(Handler handler, String urlpath) {
new Thread() {
@Override
public void run() {
//获取okHttp对象get请求,https://imgconvert.csdnimg.cn/aHR0cHM6Ly91c2VyLWdvbGQtY2RuLnhpdHUuaW8vMjAyMC81LzgvMTcxZjM1NzYyNTliM2ZkNw?x-oss-process=image/format,png
Message msg = new Message();
msg.what = -1;
msg.obj = null;
try {
//urlpath为空返回
if (urlpath == null || urlpath.length() < 1)
return;
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置连接超时为5秒
conn.setConnectTimeout(5000);
// 设置请求类型为Get类型
conn.setRequestMethod("GET");
// 判断请求Url是否成功
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
else
msg.what = 200;
//读取图片数据保存到Bitmap中,下面是添加图片资源的方法
//AppCompatImageView imageView;
//imageView.setImageBitmap();
InputStream inStream = conn.getInputStream();
byte[] bt = read(inStream);
inStream.close();
Bitmap bitmap = BitmapFactory.decodeByteArray(bt, 0, bt.length);
//加图片资源放在msg.obj中传过去
msg.obj = bitmap;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
handler.sendMessage(msg);
}
}
}.start();
}
//做get方法,header是请求头信息,property是参数信息
public static void get(Handler handler, String urlpath, Map<String, String> header, Map<String, String> property) {
new Thread() {
@Override
public void run() {
//获取okHttp对象get请求,https://imgconvert.csdnimg.cn/aHR0cHM6Ly91c2VyLWdvbGQtY2RuLnhpdHUuaW8vMjAyMC81LzgvMTcxZjM1NzYyNTliM2ZkNw?x-oss-process=image/format,png
Message msg = new Message();
msg.what = -1;
msg.obj = null;
try {
if (urlpath == null || urlpath.length() < 1)
return;
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置连接超时为5秒
conn.setConnectTimeout(5000);
// 设置请求类型为Get类型
conn.setRequestMethod("GET");
//请求头:
//connection.setRequestProperty("Content-Type", "application/json");
//connection.setRequestProperty("Accept", "application/json");
if (header != null) {
for (String key : header.keySet()) {
conn.setRequestProperty(key, header.get(key));
}
}
//如果是GET请求,将参数添加到URL后面
if (property != null) {
String parms = null;
for (String key : property.keySet()) {
parms += key + "=" + property.get(key) + "&";
}
parms = parms.substring(0, parms.length() - 1);
conn.setRequestProperty("Query", parms);
}
// 如果是POST请求,将参数添加到请求体中
// 判断请求Url是否成功
if (conn.getResponseCode() != 200) {
System.out.println("网络加载错误:请求url失败");
return;
}
InputStream inStream = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = inStream.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
//byte[] bt = StreamTool.read(inStream);
inStream.close();
message.close();
String data = new String(message.toByteArray());
System.out.println("字符串数据:" + data);
msg.obj = data;
} catch (Exception e) {
System.out.println("网络加载错误:"+ e.getMessage());
} finally {
handler.sendMessage(msg);
}
}
}.start();
}
//发送Post请求
public static void post(Handler handler, String urlpath, byte[] body,Map<String, String> header, Map<String, String> property) {
new Thread() {
@Override
public void run() {
//获取okHttp对象get请求,https://imgconvert.csdnimg.cn/aHR0cHM6Ly91c2VyLWdvbGQtY2RuLnhpdHUuaW8vMjAyMC81LzgvMTcxZjM1NzYyNTliM2ZkNw?x-oss-process=image/format,png
Message msg = new Message();
msg.what = -1;
msg.obj = null;
try {
if (urlpath == null || urlpath.length() < 1)
return;
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置连接超时为5秒
conn.setConnectTimeout(5000);
// 设置请求类型为Post类型
conn.setRequestMethod("POST");
//设置运行输入,输出:
conn.setDoOutput(true);
conn.setDoInput(true);
//Post方式不能缓存,需手动设置为false
conn.setUseCaches(false);
//请求头:
//connection.setRequestProperty("Content-Type", "application/json");
//connection.setRequestProperty("Accept", "application/json");
if (header != null) {
for (String key : header.keySet()) {
conn.setRequestProperty(key, header.get(key));
}
}
// 如果是POST请求,将参数添加到请求体中
//获取输出流,发送body数据
OutputStream out = conn.getOutputStream();
out.write(body);
out.flush();
// 判断请求Url是否成功
if (conn.getResponseCode() != 200) {
System.out.println("网络加载错误:请求url失败");
return;
}
InputStream inStream = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = inStream.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
//byte[] bt = StreamTool.read(inStream);
inStream.close();
message.close();
String data = new String(message.toByteArray());
System.out.println("字符串数据:" + data);
msg.obj = data;
} catch (Exception e) {
System.out.println("网络加载错误:"+ e.getMessage());
} finally {
handler.sendMessage(msg);
}
}
}.start();
}
public static byte[] read(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}