使用Android向API发送信息

时间:2012-07-09 18:08:10

标签: java android

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

这就是我所拥有的:

public class http extends 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类型的变量吗?这里发生了什么......?

1 个答案:

答案 0 :(得分:4)

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

1)在HttpResponse response = httpclient.execute(httppost);

之后立即移动这些陈述
 TextView myTextView = (TextView) findViewById(R.id.myTextView);
   myTextView.setText(response);

2)在尝试之外定义HttpResponse响应。

编辑:当您在try块外部定义WindyB时,请确保null检查以避免NullPointerException

阅读此link