在执行api调用和Android应用程序时出错是崩溃

时间:2013-04-25 11:15:29

标签: android

我是Android的新手,我正在尝试使用php进行api调用,我已经为它做了一个例子,在另一台计算机上工作正常,但同样的应用程序包在我的笔记本电脑上的eclipse中出错。

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", "Hi"));
        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
    }
} ` 

听到我的错误日志,我收到了很多错误。

2 个答案:

答案 0 :(得分:0)

//Try following way    
//List<NameValuePair> nameValuePairs 
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost(url);
UrlEncodedFormEntity obj=new UrlEncodedFormEntity(nameValuePairs);
obj.setChunked(true);
hp.setEntity(obj);
HttpResponse hr = hc.execute(hp);   
HttpEntity he = hr.getEntity(); 

答案 1 :(得分:0)

Logcat很明确:Could not find a method postData(View) in the activity class。我猜你已经使用xml布局来设置按钮动作。

在这种情况下,只需更改

即可
public void postData() {
}

public void postData(View view) {
}

注意:以这种方式设置按钮监听器效率不高。

此外,您应该在另一个线程上执行网络操作 - 在主线程上使用网络将在Android 3.0 +上引发NetworkOnMainThreadException