postData无法解析为某种类型

时间:2011-05-11 20:07:10

标签: java android httpclient

我是Android编程的新手。我正在尝试使用post将一些数据发布到服务器。我用Google搜索并提出了这个问题:

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”,@ expected
  • 上的语法错误

我正在使用Eclipse,我使用Shift + Ctrl + o来获取所有导入。

1 个答案:

答案 0 :(得分:1)

你的问题(基于你目前给出的信息)是你在一个类之外声明函数postData

Java中的函数需要在类中声明。或者,你通过让一个}太多(在这种情况下你应该在额外的}有错误),或者你没有宣布一个类,意外地关闭了上一课。 / p>

该课程可能如下所示:

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
        }

   }
}