
/**
* 点击事件(Get请求)
*/
findViewById(R.id.sendGetReq).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LogUtil.e("发送Get请求");
String result = null; //Get请求返回结果
String argUrl = "请求url";
// 需要传给服务端的数据
Map<String, String> mapData = new HashMap<>();
mapData.put("张三", "23");
mapData.put("李四", "24");
mapData.put("王五", "25");
try {
// 发送Get请求
result = HttpUtils.getWithParams(argUrl, mapData, null);
} catch (IOException e) {
e.printStackTrace();
}
// 拿到返回结果 做业务逻辑处理(json格式)
JSONObject resultJson = JSONObject.parseObject(result);
String resultKey = resultJson.getString("需要校验的返回值");
if (!resultKey.equals("1")) {
LogUtil.e("请求失败...");
return;
}
LogUtil.e("请求成功!");
return;
}
});package com.gaojc.text.Utils;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpUtils {
public static String getWithParams(String argUrl, Map<String, String> headers, Map<String, String> params, Proxy proxy) throws IOException {
String requestUrl = getRequestUrl(argUrl, params);
return get(requestUrl, headers, proxy);
}
public static String getRequestUrl(String url, Map<String, String> params) {
try {
StringBuilder sb = new StringBuilder();
sb.append(url);
// 返回指定字符在字符串中第一次出现处的索引位置,如果此字符串中没有这个字符,则返回-1
if (url.indexOf("&") > 0 || url.indexOf("?") > 0) {
sb.append("&");
} else {
sb.append("?");
}
for (Map.Entry<String, String> urlParams : params.entrySet()) {
String value = urlParams.getValue();
// 对参数进行utf-8编码
String urlValue = null;
if (value != null) {
urlValue = URLEncoder.encode(value, "UTF-8");
}
sb.append(urlParams.getKey()).append("=").append(urlValue).append("&");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return url;
}
public static String get(String argUrl, Map<String, String> headers, Proxy proxy) throws IOException {
LogUtil.e("请求的url是:" + argUrl);
InputStream is = null; //字节输入流,用来将文件中的数据读取到java程序中
ByteArrayOutputStream os = null; //byte数组缓冲区,用来捕获内存缓冲区的数据
HttpURLConnection urlConnection = null; //网络请求连接
try {
// 将url转换为URL类对象
URL url = new URL(argUrl);
// 打开url连接 得到urlConnection对象
if (proxy == null){
urlConnection = (HttpURLConnection) url.openConnection();
}else {
urlConnection = (HttpURLConnection) url.openConnection(proxy);
}
// 设置连接
urlConnection.setRequestMethod("GET"); //设置请求方式
urlConnection.setConnectTimeout(20000); //设置连接超时时间
urlConnection.setReadTimeout(20000); //设置读取超时时间
urlConnection.setDoInput(true); //设置是否从HttpURLConnection读入
urlConnection.setUseCaches(false); //不使用缓存
// 设置请求头信息
if (headers != null){
for (Map.Entry<String, String> entry : headers.entrySet()) {
urlConnection.setRequestProperty(entry.getKey(),entry.getValue());
}
}
// 连接
urlConnection.connect();
// 得到响应码
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
// 得到响应流
is = urlConnection.getInputStream();
os = new ByteArrayOutputStream();
// 创建字节数组 用于缓存
byte[] tmp = new byte[1024];
// 将内容读到tmp中 读到末尾为-1
int i = is.read(tmp);
while (i > 0){
os.write(tmp,0,i);
i = is.read(tmp);
}
// 获取内存缓冲区的数据
byte[] bs = os.toByteArray();
// 转换为字符串
return new String(bs);
}
// 抛出错误状态码
throw new IOException("responseCode:" + responseCode);
} catch (Exception e) {
// 抛出错误信息
throw e;
}finally {
// 关闭资源
if (is != null){
is.close();
}
if (os != null){
os.close();
}
if (urlConnection != null){
urlConnection.disconnect();
}
}
}
} /**
* 假设点击事件(Post请求)
*/
findViewById(R.id.sendPostReq).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LogUtil.e("发送Post请求...");
String result = null; //Post请求返回结果
String argUrl = "请求url";
/**
* 这里数据一般都是JSON
* 所在app的 build.gradle 里面引用JSONObject类:api 'com.alibaba:fastjson:1.2.76'
* JSON数据转为String类型传递即可
*/
// 需要传给服务端的数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("张三", "23");
jsonObject.put("李四", "24");
jsonObject.put("王五", "25");
String param = jsonObject.toJSONString();
try {
// 发送post请求
result = HttpUtils.postWithJson(argUrl, null, param, null);
} catch (IOException e) {
e.printStackTrace();
}
// 对结果进行处理
JSONObject resultJsonObject = null;
resultJsonObject = JSONObject.parseObject(result);
// 获取key属性的值 后续做业务逻辑处理
String value = resultJsonObject.getString("key");
if (!value.equals("1")) {
LogUtil.e("请求失败");
return;
}
// 继续走业务
LogUtil.e("请求成功");
return;
}
});package com.gaojc.text.Utils;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpUtils {
public static String postWithJson(String argUrl, Map<String, String> headers, String jsonStr, Proxy proxy) throws IOException {
if (headers == null) {
headers = new HashMap<>();
}
headers.put("Content-Type", "application/json"); //发送数据类型
headers.put("Charset", "UTF-8"); //发送请求编码类型
headers.put("Connection", "Close"); //不使用长链接
return post(argUrl, headers, jsonStr, proxy);
}
public static String post(String argUrl, Map<String, String> headers, String postData, Proxy proxy) throws IOException {
InputStream is = null; //字节输入流,用来将文件中的数据读取到java程序中
BufferedWriter writer = null; //字符缓冲输出流,将文本写入字符输出流,缓冲字符
ByteArrayOutputStream os = null; //byte数组缓冲区,用来捕获内存缓冲区的数据
HttpURLConnection connection = null; //网络请求连接
try {
// 将url转换为URL类对象
URL url = new URL(argUrl);
// 打开url连接
if (proxy == null) {
connection = (HttpURLConnection) url.openConnection();
} else {
connection = (HttpURLConnection) url.openConnection(proxy);
}
// 连接设置
connection.setRequestMethod("POST"); //设定请求的方法为POST,默认是GET
connection.setConnectTimeout(20000); //设置连接主机超时(单位:毫秒)
connection.setReadTimeout(20000); //设置从主机读取数据超时(单位:毫秒)
connection.setDoOutput(true); //设置是否向HttpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
connection.setDoInput(true); //设置是否从HttpUrlConnection读入,默认情况下是true;
connection.setUseCaches(false); //Post请求不能使用缓存
// 设置请求头信息
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 连接
connection.connect();
// 向字符缓冲流写入数据
if (postData != null) {
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(postData);
writer.close();
}
// 得到响应码
int responseCode = connection.getResponseCode();
// 请求成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 得到响应流
is = connection.getInputStream();
os = new ByteArrayOutputStream();
// 创建字节数组 用于缓存
byte[] tmp = new byte[1024];
// 将内容读到tmp中 读到末尾为-1
int i = is.read(tmp);
while (i > 0) {
os.write(tmp, 0, i);
i = is.read(tmp);
}
// 获取内存缓冲区的数据
byte[] bs = os.toByteArray();
// 转换为字符串
return new String(bs);
}
// 抛出错误状态码
throw new IOException("responseCode:" + responseCode);
} catch (Exception e) {
// 抛出错误信息
throw e;
} finally {
// 关闭资源
if (is != null)
is.close();
if (writer != null)
writer.close();
if (os != null)
os.close();
if (connection != null)
connection.disconnect();
}
}
}