以下是一个简单的Android网络请求工具类,可以方便地进行网络请求。
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HttpUtils {
private static Handler mHandler = new Handler(Looper.getMainLooper());
/**
* 发送GET请求
*
* @param url 请求URL
* @param params 请求参数
* @param callback 回调函数
*/
public static void sendGet(String url, HashMap<String, String> params, final HttpCallback callback) {
if (TextUtils.isEmpty(url)) {
return;
}
if (params != null && !params.isEmpty()) {
url += "?" + getParams(params);
}
final HttpURLConnection connection = getConnection(url, "GET");
final String response = getResponse(connection);
if (callback != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onResponse(response);
}
});
}
}
/**
* 发送POST请求
*
* @param url 请求URL
* @param params 请求参数
* @param callback 回调函数
*/
public static void sendPost(String url, HashMap<String, String> params, final HttpCallback callback) {
final HttpURLConnection connection = getConnection(url, "POST");
if (params != null && !params.isEmpty()) {
String json = JSON.toJSONString(params);
byte[] bytes = json.getBytes();
connection.getOutputStream().write(bytes);
}
final String response = getResponse(connection);
if (callback != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onResponse(response);
}
});
}
}
/**
* 获取请求参数
*
* @param params 请求参数
* @return
*/
private static String getParams(HashMap<String, String> params) {
if (params == null || params.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
String result = sb.toString();
if (result.endsWith("&")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* 获取HttpURLConnection对象
*
* @param url 请求URL
* @param method 请求方法,GET或POST
* @return
*/
private static HttpURLConnection getConnection(String url, String method) {
HttpURLConnection connection = null;
try {
URL mURL = new URL(url);
connection = (HttpURLConnection) mURL.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Connection", "Keep-Alive");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
/**
* 获取响应结果
*
* @param connection HttpURLConnection对象
* @return
*/
private static String getResponse(HttpURLConnection connection) {
StringBuilder sb = new StringBuilder();
try {
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
isr.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* Http请求回调函数
*/
public interface HttpCallback {
void onResponse(String response);
}
}
使用方法:
// 发送GET请求
HttpUtils.sendGet("http://example.com/path", null, new HttpUtils.HttpCallback() {
@Override
public void onResponse(String response) {
// 处理响应结果
}
});
// 发送POST请求
HashMap<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
HttpUtils.sendPost("http://example.com/path", params, new HttpUtils.HttpCallback() {
@Override
public void onResponse(String response) {
// 处理响应结果
}
});
注意:在Android中不能在主线程中执行网络请求,需要在子线程或异步任务中执行。本文示例代码中的HttpUtils
工具类只提供网络请求相关的代码逻辑,因此没有涉及到线程相关的代码。在实际使用时,建议在异步任务中调用HttpUtils
工具类的相关方法。
在 Android 开发中,经常需要跟网络打交道,请求数据、上传图片、下载文件等操作都要用到网络请求工具类。以下是一个简单的封装了 OkHttp 的网络请求工具类,可以供参考:
public class HttpUtil {
private static final String TAG = "HttpUtil";
public static void get(String url, Callback callback) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(callback);
}
public static void post(String url, RequestBody body, Callback callback) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(callback);
}
public static void postJson(String url, String json, Callback callback) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(callback);
}
}
其中,get() 方法用于发起 GET 请求,post() 方法用于发起 POST 请求,postJson() 方法则用于发起 POST 请求并传递 JSON 数据。
这是一个比较简单的网络请求工具类,大家可以根据自己的需求进行扩展和修改。在使用时,只需要调用对应的方法并提供相应的参数即可。如下面的示例代码:
HttpUtil.get("https://www.baidu.com", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "request failed!" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "response body:" + response.body().string());
}
});
String json = "{"name":"zhangsan", "age":20}";
HttpUtil.postJson("https://httpbin.org/post", json, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "request failed!" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "response body:" + response.body().string());
}
});
上面的代码分别使用了 get() 和 postJson() 方法发起了 GET 和 POST 请求,并在回调函数中处理了响应结果。需要注意的是,在回调中处理响应结果的时候,需要在子线程中执行,否则会抛出异常。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/157936.html