2013-10-09 77 views
0

在我的應用程序我需要發佈數據到一個網址註冊一個新的用戶。這裏是URLAndroid發佈數據通過url

http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG] 

如果我這樣做,我正確的應該得到這個消息:

{"success":true,"error":null} 
or if not {"success":false,"error":"parameters"} 

有人可以指導我這一點,並告訴我,我該怎麼辦了。

回答

3

第一:
你需要在一個異步線程執行所有的網絡任務使用:

public class PostData extends AsyncTask<String, Void, String>{ 
{ 
     @Override 
    protected String doInBackground(String... params) { 
    //put all your network code here 
} 

二:
創建HTTP請求: 我我在這裏假設電子郵件,用戶名和IMG作爲變量。

String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]"; 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(server); 

      //httppost.setHeader("Accept", "application/json"); 
      httppost.setHeader("Accept", "application/x-www-form-urlencoded"); 
      //httppost.setHeader("Content-type", "application/json"); 
      httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 

third:  
// Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));  
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); 

      try { 
       HttpResponse response =httpclient.execute(httppost); 

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

現在簡單地查詢您的響應處理程序,即在這種情況下的響應。

不要忘記添加INTERNET權限在AndroidManifest.xml中

希望這有助於!

+0

謝謝你的好回答 –

+0

太好回答朋友..... –

0

使用HTTP client類,並通過特定URI constructor.格式化你的URL創建一個HTTP post,選擇設置實體,頭部等,通過客戶端執行後,收到HTTP response,拉entity出來的響應和處理的它。

編輯例如:

HttpClient httpclient = new DefaultHttpClient(); 
URI uri = new URI("http", 
     "www.google.com", // connecting to IP 
     "subpath", // and the "path" of what we want 
     "a=5&b=6", // query 
     null); // no fragment 
HttpPost httppost = new HttpPost(uri.toASCIIString); 
// have a body ? 
// post.setEntity(new StringEntity(JSONObj.toString())); 
// post.setHeader("Content-type", "application/json"); 
HttpResponse response = httpClient.execute(post); 
int statusCode = response.getStatusLine().getStatusCode(); 
HttpEntity entity = response.getEntity(); 
Reader r = new InputStreamReader(entity.getContent()); 
// Do something with the data in the reader. 
+0

你能舉個例子怎麼做嗎? –