2012-07-09 47 views
0

我正在尝试联系API并获取响应。作为我的调试的一部分,我想确保响应被记录,它应该是一个XML响应。使用Android向API发送信息

这是我有:

公共类HTTP扩展活动{

public void httpMethod(){ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://site.com/api/"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("apikey", "0d4e122d20")); 

     nameValuePairs.add(new BasicNameValuePair("ip", "65.82.126.103")); 
     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 
    } 

    TextView myTextView = (TextView) findViewById(R.id.myTextView); 
    myTextView.setText(response); 
} 
} 

我想看到我得到的回应,但在该行的变量响应

myTextView.setText(response) 

正在丢出错误:

response cannot be resolved to a variable 

响应不是真正的httpresponse类型的变量吗?这里发生了什么...?

回答

4

响应变量的作用域仅在try块内。两种方式解决此问题:

1)把这些语句之后HttpResponse response = httpclient.execute(httppost);

TextView myTextView = (TextView) findViewById(R.id.myTextView); 
    myTextView.setText(response); 

2)定义HttpResponse反应出方的尝试。

编辑:由于WindyB指定当你在尝试块外定义时,确保null检查以避免NullPointerException

阅读本link

+0

或者,澄清甚至更多:你应该申报“的HttpResponse响应”你try块之外。请确保在您的catch语句或您的应用程序偶尔会发生NullPointerException异常后执行空检查。 – WindyB 2012-07-09 18:15:16

+0

您已回答我的官方问题并修复了我的错误。我无法相信自己错过了...但是我希望你能为我解答这个问题......没有什么会被展示出来。它进入下一个屏幕,但没有给出响应。我没有正确使用这些功能吗? (我允许在清单中访问互联网) – GK1667 2012-07-09 18:30:38

+0

,也许它与修正错误有关。它让我把它投射到CharSeq进行编译。所以它看起来像myTextView.setText((CharSeq)响应); – GK1667 2012-07-09 18:34:08