我是 Android 编程新手。我正在尝试使用 post 将一些数据发布到服务器。我用谷歌搜索并想出了这个:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
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);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
我的问题是我在这段代码的第一行遇到错误:
- postData 无法解析为类型
- 标记“{”存在语法错误,请删除此标记
- 标记“void”存在语法错误,@预期
我正在使用 Eclipse,并使用 Shift+Ctrl+o 来获取所有导入。
最佳答案
您的问题(根据您目前提供的信息)是您在类外部声明函数 postData
。
Java中的函数需要在类中声明。要么,您因使用过多的 }
而意外关闭了前一类(在这种情况下,您应该在额外的 }
处出现错误),或者您还没有t 声明了一个类。
该类可能如下所示:
public class MyPoster {
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
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);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
关于java - postData 无法解析为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5969983/