Android构造和语法错误

时间:2012-07-09 16:45:22

标签: java android

我在网上找到了这个示例代码。它似乎做我想要的,向API发出请求,我只需要稍微定制它。

然而,当我尝试编译它时,它给了我三行相同的错误

 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行抛出错误

1 个答案:

答案 0 :(得分:2)

除了Ran所说的内容之外:您可能希望首先学习一些基本的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”方法。