0

我在网上找到了这个示例代码。它似乎可以做我想做的事,向 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 行引发错误

4

1 回答 1

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 Activity 调用它的“myMethodName”方法。

于 2012-07-09T16:58:44.953 回答