我正在尝试联系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类型的变量吗?这里发生了什么......?
答案 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