我正在试着做一个小程序来和我的Lifx灯泡互动。我有一个类灯泡,我做了一个runnable:
public Runnable runnableToggle = new Runnable() {
@Override
public void run() {
try {
String url = "https://api.lifx.com/v1/lights/" + Bulb.this.ID + "/toggle/";
URL obj = null;
try {
obj = new URL(url);
} catch (MalformedURLException e) {
System.out.println("Malformed URL");
e.printStackTrace();
}
assert obj != null;
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
String authS = "Bearer MY_TOKEN";
con.setRequestProperty("Authorization", authS);
con.setRequestMethod("POST");
con.setDoOutput(true);
} catch (Exception e) {
e.printStackTrace();
}
}
};然而,当我调用这个窗体我的主类时,它不工作。
Thread t = new Thread(deskBulb.runnableToggle);
t.start();程序只会执行,不会打印任何错误。
如果我在类中运行与“普通”函数完全相同的代码,它就可以工作。
我以前没有使用过runnables,所以可能是个愚蠢的错误。无论如何,感谢任何回答的人的帮助。
发布于 2018-02-26 00:24:41
如果您的代码运行时没有错误,问题可能来自服务REST,请尝试添加响应代码返回以查看有关返回的更多信息:
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());发布于 2018-02-25 23:47:22
您的类Bulb应该实现一个Runnable接口,然后像这样实现run方法:
public class Bulb implements Runnable{
...
@Override
public void run() {
// add your logic here
}
...
}然后,创建您的类的一个实例,并启动thread:
Bulb bulb = new Bulb();
Thread t = new Thread(bulb );
t.start();https://stackoverflow.com/questions/48975260
复制相似问题