You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Java如何直接执行HTTP命令实现自定义设备重启?

自定义设备重启HTTP请求失败排查

已实现的正常登录流程

登录使用的HTTP请求:

http://x.x.x.x/cgi-bin/web.cgi?action=API&action2=Login&param1=username&param2=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&param1=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&param1=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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:15:30