2017-08-24 52 views
3

我想使用curl和登錄驗證在交換機單擊監聽器上發出OFF命令。 像http://admin:[email protected]/outlet?4=OFF如何在Android中使用curl?

我設置點擊開關聽者這樣和點擊收聽我呼籲捲曲一個方法現在

switch4.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       getRequest(); 

      } 
     }); 

,Request()方法的方法是這樣的...

public static String getRequest() { 
     StringBuffer stringBuffer = new StringBuffer(""); 
     BufferedReader bufferedReader = null; 
     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(); 

      URI uri = new URI("http://10.1.1.83/outlet?4=OFF"); 
      httpPost.setURI(uri); 
      httpPost.addHeader(BasicScheme.authenticate(
        new UsernamePasswordCredentials("admin", "1234"), 
        HTTP.UTF_8, false)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      InputStream inputStream = httpResponse.getEntity().getContent(); 
      bufferedReader = new BufferedReader(new InputStreamReader(
        inputStream)); 

      String readLine = bufferedReader.readLine(); 
      while (readLine != null) { 
       stringBuffer.append(readLine); 
       stringBuffer.append("\n"); 
       readLine = bufferedReader.readLine(); 
      } 
     } catch (Exception e) { 
      // TODO: handle exception 
     } finally { 
      if (bufferedReader != null) { 
       try { 
        bufferedReader.close(); 
       } catch (IOException e) { 
        // TODO: handle exception 
       } 
      } 
     } 
     return stringBuffer.toString(); 
    } 
+1

問題是什麼? – bezet

+0

閱讀我的代碼和描述 –

+0

我想在android –

回答

2

您可以使用httpget方法和用戶名,密碼憑證。 在這裏,我告訴你的方法。

public static String getRequest() { 
    StringBuffer stringBuffer = new StringBuffer(""); 
    BufferedReader bufferedReader = null; 
try { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(); 

     URI uri = new URI("http://10.1.1.83/outlet?2=OFF"); 
     httpGet.setURI(uri); 
     httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("admin", "1234"), 
       HTTP.UTF_8, false)); 

     HttpResponse httpResponse = httpClient.execute(httpGet); 
     InputStream inputStream = httpResponse.getEntity().getContent(); 
     bufferedReader = new BufferedReader(new InputStreamReader(
       inputStream)); 

     String readLine = bufferedReader.readLine(); 
while (readLine != null) { 
      stringBuffer.append(readLine); 
      stringBuffer.append("\n"); 
      readLine = bufferedReader.readLine(); 
     } 
    } catch (Exception e) { 
// TODO: handle exception 
    } finally { 
if (bufferedReader != null) { 
try { 
       bufferedReader.close(); 
      } catch (IOException e) { 
// TODO: handle exception 
      } 
     } 
    } 
return stringBuffer.toString(); 
} 

在腳本中使用此代碼,它會工作。

+0

Thnx很多..像魅力一樣工作.. –