2016-07-24 43 views
-1

我需要一個簡單的androd應用程序,它向服務器發送一個單詞並從服務器接收答案。我創建了一個窗體,它有兩行和一個按鈕。在第一行中,用戶寫下單詞並單擊按鈕。在這段時間,應用程序發送這個詞到服務器。當服務器發回響應時,我們顯示這個響應在其他行中。post android簡單的應用程序

我對一些代碼,但是這個代碼不能在android 23上工作。我也嘗試通過改進來做到這一點,但是我對這個配件的下面有一些問題。

我知道只需要使用POST,但不知道如何。

我可以發送我的android的IP地址到服務器?

+0

份額的代碼,是什麼你有沒有試過 – SaravInfern

+0

https://yadi.sk/d/UC-eEoo4ta3hV 它是一個java文件。 – nuser

回答

0

試試這個代碼: 它還將從該頁面返回的響應作爲字符串

public static String postRequest(String post_url, String data) { 
     try { 
      URL url = new URL(post_url); 
      HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
      BufferedReader br; 
      StringBuilder sb = new StringBuilder(); 
      String line; 

      connection.setDoOutput(true); 
      connection.setRequestMethod("POST"); 
      connection.setReadTimeout(10000); 
      Writer writer = new OutputStreamWriter(connection.getOutputStream()); 
      writer.write(data); 
      writer.flush(); 
      writer.close(); 

      if (200 <= connection.getResponseCode() && connection.getResponseCode() <= 299) { 
       br = new BufferedReader(new InputStreamReader((connection.getInputStream()))); 
      } else { 
       br = new BufferedReader(new InputStreamReader((connection.getErrorStream()))); 
      } 

      while ((line = br.readLine()) != null) { 
       sb.append(line); 
      } 

      return sb.toString(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

並通過調用它:

postRequest("http://your-url", "name=value&anothername=somevalue"); 
0

我覺得凌空將滿足您的需求,這是一個非常簡單的庫,可以處理異步請求:

https://developer.android.com/training/volley/index.html

「我可以將我的android的ip地址發送到服務器嗎?」

當然,讓你的Android IP只需使用一個這樣的代碼在服務器端,假設你使用PHP:

<? 
    $ip = $_SERVER["REMOTE_ADDR"]; 
    echo "<br />Your IP is : $ip"; 
?> 

編輯:NodsJS例如

app.post('/getip', function (req, res) { 
    var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress || 
     req.connection.socket.remoteAddress; 
}) 
+0

感謝您的鏈接。 我需要使用node.js服務器,如果你有一些鏈接信息如何在node.js上使用ip,我會很感激。 – nuser