2015-10-05 25 views
1

我有一個簡單的表單,我需要將它發送到帶有參數的URL。使用GET發送表單到URL

比方說,我有一個參數調用令牌,我想將其發送到example.com/?token=the_token

我並不需要處理或獲取輸出,只需將其發送給該網址。

我該怎麼做?我一直在嘗試使用URLCONNECTION和HTTPURLCONNECTION幾個小時,沒有任何工作。

因爲我嘗試了很多東西,沒有任何工作,我正在嘗試從頭開始。 這是它:

if (token.isEmpty()) { 
       getGCMToken(); 
     } else { 
      //Send the token to example.com/?token=token. The URL will add the token to my database with PHP. 

     } 

請不要DefaultHttpClient回覆。它已被棄用。

嘗試的URLConnection():

if (token.isEmpty()) { 
       getGCMToken(); 
     } else { 
      //Send the tokeb to example.com/?token=token 
      URLConnection connection = null; 
      try { 
       connection = new URL("mysite.com/send.php?id=my_id").openConnection(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      connection.setRequestProperty("Accept-Charset", "UTF-8"); 
      try { 
       InputStream response = connection.getInputStream(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
+0

你的意思是HTTP POST請求? – penta

+0

這聽起來像你應該使用POST的 – EpicPandaForce

+0

編輯鏈接:這些問題通常會得到大量downvoted,但我仍然會幫助你,看看http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view = article_discription&aid = 64&aaid = 89 – penta

回答

0

看,我去年建了一個完整的web/http通信類。我複製你與GET(S)涉及塊:

導入至少有以下:

import java.net.HttpURLConnection; 
import java.net.URL; 
import java.io.BufferedInputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.InputStream; 
import java.io.OutputStreamWriter; 

try{ 
    String mainUrl = "<your_url>"; 

    String query = "?" + "<add_your_params_here>"; 

    URL url = new URL (mainUrl + query); 

    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); 

    InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 

    // If you want to process the response you have to do something the the in InputStream. But ommiting it here, as you said you won't use the response. 
} 
catch (FileNotFoundException fnf){ 
     Log.e("Incorrect Url", "Resource was not found"); 
} 
catch (Exception e){ 

} 

還有要記得添加Internet同意您的Android清單XML文件:android.permission 。互聯網

檢查這個響應添加網絡權限:What permission do I need to access Internet from an android application?

+0

應用程序不會崩潰,但它什麼都不做 - 我的.php文件沒有被訪問,查詢也沒有運行 – EliKo

+0

我已經添加了上面的導入。檢查你至少有這些。 – MarkSkayff

+0

我的IDE自動導入所有這些包,這不是問題。 – EliKo

0

使用URLConnection這一點。

URLConnection connection = new URL(url + "?" + query).openConnection(); 
connection.setRequestProperty("Accept-Charset", charset); 
InputStream response = connection.getInputStream(); 
+0

我的應用程序崩潰了 – EliKo

+0

你填寫了'url','query'和'charset'變量嗎? –

+0

張貼您的EXACT代碼 –