我有一个定制设备,它通过热点与我的手机相连,通过我的应用程序,我可以正确地连接和登录到那个定制设备,如下所示:
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) {
我可以得到正确的responseCode = 200
,这是可以的.
然后,我try 发送另一个HTTP URL以try 重新启动该自定义设备,如下所示:
http://x.x.x.x/cgi-bin/web.cgi?session_id=xxxxxxxxxx&action=API&action2=value1¶m1=RESTART
用作帖子:
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)
应该"执行"该URL,并使该定制设备重新启动…
我还try 使用lambda将此代码放在线程内部,如下所示:
Thread = () -> {}
为了避免IOException
次在DialogFragment的主要活动中运行它,但它不起作用.
有没有可能在不使用任何第三部分的情况下执行该http的方法?还是因为HttpURLConnection不适合这个目标,所以我必须只使用第三部分来实现这个目标?谢谢!干杯
EDIT:个
我还try 使用排球库执行StringRequest,如下所示:
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();
但这两种方式都不起作用,即使我安顿了下来……也许我错过了什么需要考虑的地方?…