2016-09-30 40 views
-1

我想用一个按钮来调用一个链接,打开和关闭一个领导调用链接Android应用程式

令我带领:

http://10.0.0.3/light4on

令我带领了:

http://10.0.0.3/light4off

public void onClick(View v){ 

     String link = "http://10.0.0.3/light4off"; 
     try { 
      URL u = new URL(link); 
      HttpURLConnection http = (HttpURLConnection)u.openConnection(); 
      // http.connect(); 
      ausgabe.setText("working"); 

     } catch (Exception e) 
     { 
      ausgabe.setText("not working"); 
     } 

    } 

但这isn't工作...

我也加入到这个清单:

+0

这似乎NAT IP,您的计算机可能有机会获得它,当你使用浏览器。确保你的android也可以访问它,试着用android手机中的浏览器打开它,看看它是否工作。 –

+0

它正在与Android浏览器 –

回答

0

你可以叫你正在使用HttpUrlConnectionOkHttp

首先,呼吁在你的Android应用程序URL任何API,请求许可到接入网,添加下列内容的清单:

<uses-permission android:name="android.permission.INTERNET" /> 

以下的AsyncTask将被用来调用HTTP GET方法API中单独的线程:

class RequestTask extends AsyncTask<String, String, String>{ 
    String server_response; 

    @Override 
    protected String doInBackground(String... uri) { 
    URL url; 
     HttpURLConnection urlConnection = null; 

     try { 
      url = new URL(uri[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 

      int responseCode = urlConnection.getResponseCode(); 

      if(responseCode == HttpURLConnection.HTTP_OK){ 
       server_response = readStream(urlConnection.getInputStream()); 
       Log.v("CatalogClient", server_response); 
      } 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     //Do anything with response.. 
    } 
} 


// Converting InputStream to String 

private String readStream(InputStream in) { 
     BufferedReader reader = null; 
     StringBuffer response = new StringBuffer(); 
     try { 
      reader = new BufferedReader(new InputStreamReader(in)); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       response.append(line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return response.toString(); 
    } 


To call this class you have to write: new RequestTask().execute("http://10.0.0.3/light4on"); 
+0

谢谢! @ url = new URL(strings [0]); AS将字符串标记为错误? 抱歉愚蠢的问题。我是新来更新的Java –

+0

。现在你可以检查 – Anjali

+0

谢谢! 但它不工作... logcat说: I/System.out:(HTTPLog)-Static:isSBSettingEnabled false –

相关问题