2016-07-16 79 views
1

我是新來的Android和現在我太累了搜索關於Android的HTTP請求的最佳教程。如何從Android發送http發佈請求?

我想這些參數發送到phpServer,

  • 名稱= 「一些名」

  • 電子郵件= 「一些電子郵件」

我們能做到這一點在MainActivity.java文件中?這是否需要任何jar(庫)文件? 歡迎任何建議。

我想這一點,

@Override 
public void onClick(View view) { 
    if(view == btnSubscribe){ 
     HttpURLConnection client = null; 
     try { 
      URL url = new URL("http://www/somewebsite.com/API/SUBSCRIBE"); 
      client = (HttpURLConnection) url.openConnection(); 
      client.setRequestMethod("POST"); 
      client.setRequestProperty("name","test one"); 
      client.setRequestProperty("email","[email protected]"); 
      client.setDoOutput(true); 

      OutputStream outputPost = new BufferedOutputStream(client.getOutputStream()); 
      outputPost.flush(); 
      outputPost.close(); 
      client.setChunkedStreamingMode(0); 

     } catch(MalformedURLException error) { 
      showError("Handles an incorrectly entered UR"); 
     } 
     catch(SocketTimeoutException error) { 
      showError("Handles URL access timeout"); 
     } 
     catch (IOException error) { 
      showError("Handles input and output errors"); 
     }finally { 
      if(client != null) 
      client.disconnect(); 
     } 
    } 
} 
+0

其中代碼???? –

+1

@Sahan通過去[這](http://stackoverflow.com/help/mcve) – Nisarg

+0

@IntelliJAmiya對不起,我清除了所有的代碼,因爲我沒有工作。現在我正在一個新項目中。 – Sahan

回答

5

我使用這個代碼和工作爲好。試試這個代碼。

public static String httpPostRequest(Context context, String url, String email) { 
     String response = ""; 
     BufferedReader reader = null; 
     HttpURLConnection conn = null; 
     try { 
      LogUtils.d("RequestManager", url + " "); 
      LogUtils.e("data::", " " + data); 
      URL urlObj = new URL(url); 

      conn = (HttpURLConnection) urlObj.openConnection(); 
      conn.setRequestMethod("POST"); 
      conn.setDoOutput(true); 
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

      data += "&" + URLEncoder.encode("Email", "UTF-8") + "=" 
        + URLEncoder.encode(email, "UTF-8"); 


      wr.write(data); 
      wr.flush(); 

      LogUtils.d("post response code", conn.getResponseCode() + " "); 

      int responseCode = conn.getResponseCode(); 



      reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 

      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 

      response = sb.toString(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      LogUtils.d("Error", "error"); 
     } finally { 
      try { 
       reader.close(); 
       if (conn != null) { 
        conn.disconnect(); 
       } 
      } catch (Exception ex) { 
      } 
     } 
     LogUtils.d("RESPONSE POST", response); 
     return response; 
    } 
+0

太棒了!它工作 – Sahan

+0

不知道你在哪裏定義'數據' – lucidbrot

0

首先,最httpClint現在已經過時,所以如果你現在可以使用HttpURLConnection類的相同。

你可以參考 here

,如果你想使用的庫,那麼你可以使用

這兩個是最好的圖書館。

乾杯