我在网上找到了这个示例代码。它似乎做了我想做的事情,向 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 行引发错误
最佳答案
除了 Ran 所说的之外:您可能想先学习一些基本的 Java 编程类(class)/教程。一些与编程相关的教程假设您已经熟悉这一点,并且只列出了几行不能直接使用的代码,因为它们属于方法内部。
您需要按如下方式重写您的类(“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”方法。
关于java - Android 构造和语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11399531/