0

我正在尝试联系 API 并获得响应。作为调试的一部分,我想确保正在记录响应,它应该是一个 xml 响应。

这是我所拥有的:

公共类 http 扩展 Activity {

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

1 回答 1

4

响应变量的范围仅在 try 块内。解决此问题的两种方法:

1) 将这些语句移到后面 HttpResponse response = httpclient.execute(httppost);

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

HttpResponse2)在尝试之外定义响应。

编辑:正如 WindyB 在您在 try 块之外定义时指定的那样,请确保null检查以避免NullPointerException.

阅读此链接

于 2012-07-09T18:13:00.150 回答