2012-07-09 59 views
0

我在網上找到了這個示例代碼。它似乎做我想做的事情,向API發出請求,我只需要定製它。Android構造和語法錯誤

然而,當我嘗試編譯它,它給了我同樣的錯誤三線

Syntax error on token(s), misplaced 
construct(s) 
- Syntax error on token "setEntity", = 
expected after this token 

也許有些人能看到的東西我沒有?

下面的代碼:

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 

public class http { 

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 


    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 


} 

將引發錯誤的nameValuePairs.add線和httppost.setEntity線

+0

nameValuePairs的錯誤更改通過將「添加」引入錯誤 – GK1667 2012-07-09 16:48:16

+4

的引號中,您的代碼應該位於方法中。請閱讀java教程。 – Ran 2012-07-09 16:49:19

回答

2

除了什麼冉說:你可能想拿起一些首先要有基本的Java編程課程/教程。一些與編程相關的教程假設你已經熟悉了這些,只列出幾行不能直接使用的代碼,因爲它們屬於一個方法。

你需要重寫你的類,如下所示(「myMethodName」可以是您選擇的任何其他名稱)

public class http { 
    public void myMethodName() { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
     nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 
    } 
} 

然後這一段代碼不能被作爲被執行。您需要創建類「http」的實例,並從Android活動中調用其「myMethodName」方法。