Android Java如何直接执行HTTP命令实现自定义设备重启?
自定义设备重启HTTP请求失败排查
已实现的正常登录流程
登录使用的HTTP请求:
http://x.x.x.x/cgi-bin/web.cgi?action=API&action2=Login¶m1=username¶m2=password
对应的连接代码:
url = new URL(URLCommand); connection = (HttpURLConnection) url.openConnection(); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy; policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
该请求可正常返回200响应码,登录功能正常。
重启设备的请求尝试及问题
尝试发送以下HTTP请求触发设备重启:
http://x.x.x.x/cgi-bin/web.cgi?session_id=xxxxxxxxxx&action=API&action2=value1¶m1=RESTART
1. HttpURLConnection POST方式尝试
代码实现:
url = new URL(URLCommand); connectionForCommand = (HttpURLConnection) url.openConnection(); connectionForCommand.setRequestMethod("POST"); connectionForCommand.setDoOutput(true); BufferedReader responseReader = new BufferedReader(new InputStreamReader(connectionForCommand.getInputStream())); String responseData = responseReader.readLine();
原本预期setDoOutput(true)会执行请求并触发重启,但设备无反应。后续将代码放入线程以避免DialogFragment主线程的IOException:
new Thread(() -> { // 上述请求代码逻辑 }).start();
问题仍未解决。
2. Volley库StringRequest尝试
补充使用Volley库实现,代码如下:
new Thread(() -> { urlPostRequest = "http://x.x.x.x/cgi-bin/web.cgi?session_id=xxxxxxxxxx&action=API&action2=value1¶m1=RESTART"; try{ RequestQueue arq = Volley.newRequestQueue(getContext()); arq.getCache().clear(); StringRequest urlPostRequest = new StringRequest(Request.Method.POST, URLCommand, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject obj = new JSONObject(response); String value = obj.getString("value"); showAlert("LogCat", value.toString()); } catch(JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { showAlert("LogCat", getActivity().getResources().getString(R.string.st_errorresponse)); } }); arq.add(urlPostRequest); } catch (Exception e) { e.printStackTrace(); } }).start();
设置为POST方式后,设备依旧未重启。
疑问
- 是否无需第三方库即可实现该HTTP命令?HttpURLConnection是否无法满足需求?
- 使用Volley时是否有遗漏的配置或注意事项?
内容的提问来源于stack exchange,提问作者Luigino
相关产品推荐
相关产品推荐

