请求百度API HarmonyOS 鸿蒙Next
请求百度API HarmonyOS 鸿蒙Next
button点击时间,部署到模拟器点击按钮直接闪退。是什么原因?添加网络权限了。
更多关于请求百度API HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
楼主你好,可以试试以下自己封装的请求工具类,或者提供日志进一步分析问题:
public class NetworkManager {
private static final String TAG = "hm_NetUtil";
private static final String REQUEST_METHOD_GET = "GET";
private static final String REQUEST_METHOD_POST = "POST";
private static final String CACHE_PATH = "NetworkCache";
private static NetworkManager instance;
private Context context;
private TaskDispatcher globalTaskDispatcher;
private HttpResponseCache httpResponseCache;
private int cacheValidTime = 60 * 60 * 24;
private int connectTimeout = 10 * 1000;
private int readTimeout = 10 * 1000;
/**
* constructor of NetworkManager
*
* @param context context
*/
private NetworkManager(Context context) {
this.context = context;
globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
httpResponseCache = HttpResponseCache.getInstalled();
}
/**
* getInstance of NetworkManager
*
* @param context context
* @return NetworkManager
*/
public static NetworkManager getInstance(Context context) {
if (instance == null) {
instance = new NetworkManager(context.getApplicationContext());
}
return instance;
}
/**
* set connect time out and read time out
*
* @param connectTimeout connectTimeout
* @param readTimeout readTimeout
*/
public void setTimeout(int connectTimeout, int readTimeout) {
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
}
/**
* set cache valid time
*
* @param time time
*/
public void setCacheValidTime(int time) {
cacheValidTime = time;
}
/**
* set cache size
*
* @param size size
*/
public void setCacheSize(long size) {
File httpCacheDir = new File(context.getCacheDir(), CACHE_PATH);
try {
HttpResponseCache.install(httpCacheDir, size);
} catch (IOException e) {
LogUtil.error(TAG, e.getMessage());
}
}
/**
* add FlowStatistics Callback
*
* @param callback callback
*/
public void addFlowStatisticsCallback(FlowStatisticsCallback callback) {
String packageName = context.getBundleName();
IBundleManager iBundleManager = context.getBundleManager();
int myUid = 0;
try {
BundleInfo bundleInfoundleInfo = iBundleManager.getBundleInfo(packageName, 0);
myUid = bundleInfoundleInfo.uid;
} catch (RemoteException e) {
LogUtil.info(TAG, e.getMessage());
}
if (myUid != 0) {
long rx1 = DataFlowStatistics.getUidRxBytes(myUid);
long tx1 = DataFlowStatistics.getUidTxBytes(myUid);
int finalMyUid = myUid;
context.getGlobalTaskDispatcher(TaskPriority.DEFAULT)
.delayDispatch(
() -> {
long rx2 = DataFlowStatistics.getUidRxBytes(finalMyUid) - rx1;
long tx2 = DataFlowStatistics.getUidTxBytes(finalMyUid) - tx1;
context.getUITaskDispatcher()
.asyncDispatch(
() -> {
if (callback != null) {
callback.getFlowStatistics(tx2, rx2);
}
});
},
1000);
}
}
/**
* 链接网络,获取数据
*
* @param strUrl 请求链接
* @param callback 结果回调
*/
public void requestGet(String strUrl, ResponseCallback callback) {
globalTaskDispatcher.asyncDispatch(() -> {
HttpURLConnection connection = null;
try {
connection = getNetConnection(strUrl, REQUEST_METHOD_GET);
StringBuilder resultBuffer = new StringBuilder();
int reqCode = connection.getResponseCode();
if (reqCode == HttpURLConnection.HTTP_OK) {
InputStream dataStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(dataStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String tempLine;
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
if (callback != null) {
callback.onSuccess(resultBuffer.toString());
}
reader.close();
inputStreamReader.close();
if (dataStream != null) {
dataStream.close();
}
if (httpResponseCache != null) {
httpResponseCache.flush();
}
} else {
throw new IOException(connection.getResponseMessage());
}
} catch (Exception e) {
if (callback != null) {
callback.onFail(e.getMessage());
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
});
}
/**
* 链接网络,获取数据
*
* @param strUrl 请求链接
* @param json 信息
* @param callback callback
*/
public void requestPost(String strUrl, String json, ResponseCallback callback) {
globalTaskDispatcher.asyncDispatch(
new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
connection = getNetConnection(strUrl, REQUEST_METHOD_POST);
InputStream dataStream;
StringBuilder resultBuffer = new StringBuilder();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(json.getBytes(), 0, json.length());
int reqCode = connection.getResponseCode();
if (reqCode == HttpURLConnection.HTTP_OK) {
dataStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(dataStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String tempLine;
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
if (callback != null) {
callback.onSuccess(resultBuffer.toString());
}
reader.close();
inputStreamReader.close();
if (dataStream != null) {
dataStream.close();
}
if (httpResponseCache != null) {
httpResponseCache.flush();
}
} else {
throw new Exception(connection.getResponseMessage());
}
} catch (Exception e) {
if (callback != null) {
callback.onFail(e.getMessage());
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
});
}
/**
* 链接网络,获取数据
*
* @param host host
* @param port port
* @param content content
* @param callback callback
*/
public void requestSocket(String host, int port, String content, ResponseCallback callback) {
NetManager netManager = NetManager.getInstance(context);
NetHandle netHandle = netManager.getDefaultNet();
if (netHandle == null) {
return;
}
globalTaskDispatcher.asyncDispatch(
new Runnable() {
@Override
public void run() {
DatagramSocket socket = null;
try {
InetAddress address = netHandle.getByName(host);
socket = new DatagramSocket(port);
netHandle.bindSocket(socket);
byte[] sendByte = content.getBytes();
DatagramPacket sendDp = new DatagramPacket(sendByte, sendByte.length, address, port);
socket.send(sendDp);
context.getUITaskDispatcher()
.asyncDispatch(
() -> {
if (callback != null) {
callback.onSuccess(sendDp.toString());
}
});
} catch (IOException e) {
if (callback != null) {
callback.onFail(e.getMessage());
}
LogUtil.error(TAG, e.getMessage());
} finally {
if (socket != null) {
socket.close();
}
}
}
});
}
/**
* 获取Connection
*
* @param strUrl 请求链接
* @param method 请求方式
* @return HttpURLConnection对象
* @throws Exception e
*/
private HttpURLConnection getNetConnection(String strUrl, String method) throws Exception {
NetManager netManager = NetManager.getInstance(context);
NetHandle netHandle = netManager.getDefaultNet();
if (netHandle == null) {
throw new NullPointerException();
}
HttpURLConnection connection;
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
HostnameVerifier ignoreHostnameVerifier = (s, sslsession) -> true;
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
URL url = new URL(strUrl);
URLConnection urlConnection = netHandle.openConnection(url, java.net.Proxy.NO_PROXY);
if (urlConnection instanceof HttpsURLConnection) {
connection = (HttpsURLConnection) urlConnection;
} else if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
throw new NullPointerException();
}
connection.setRequestMethod(method);
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.addRequestProperty("Cache-Control", "max-age=0");
connection.addRequestProperty("Cache-Control", "max-stale=" + cacheValidTime);
connection.connect();
return connection;
}
更多关于请求百度API HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
问题已经解决了。谢谢😊,
看日志报错的位置,在报错位置打断点,再进行调试
闪退可以看下日志,看里面是否有报错。按照错误再去搜索问题解决方法,这样会更快。
如果搜索不到,则可以把错误日志贴出来,有大神看到了会回复的。
欢迎开发小伙伴们进来帮帮楼主
针对帖子标题“请求百度API HarmonyOS 鸿蒙Next”的问题,以下是我的回答:
在HarmonyOS(鸿蒙)系统上请求百度API,你需要确保几个关键点:
-
API兼容性:首先,确认百度API是否支持HarmonyOS系统。由于HarmonyOS是基于微内核的全场景分布式OS,与Android和iOS有所不同,因此API的调用方式或所需权限可能有所差异。
-
SDK或库:检查百度是否提供了适用于HarmonyOS的SDK或库。这些SDK或库通常会包含针对HarmonyOS系统的特定接口和调用方法。
-
权限和网络配置:确保你的HarmonyOS应用具有访问网络和执行相关API调用的权限。这包括在应用的manifest文件中声明必要的权限,以及配置正确的网络接口。
-
API调用示例:参考百度API的官方文档,了解如何在HarmonyOS环境中进行API调用。通常,这些文档会提供代码示例和调用步骤。
-
错误处理:在调用API时,务必添加错误处理逻辑,以便在调用失败时能够捕获并处理异常。
如果在尝试上述步骤后仍然无法成功请求百度API,可能是由于API版本不兼容、权限配置错误或其他系统级问题。此时,建议直接联系百度API的技术支持团队或访问其开发者论坛寻求帮助。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html