我正在尝试联系API并获得响应。作为调试的一部分,我想确保响应已被记录,它应该是xml响应。
这是我所拥有的:
公共类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类型的变量?这里发生了什么...?
最佳答案
响应变量的范围仅在try块内部。解决此问题的两种方法:
1)将这些语句移到HttpResponse response = httpclient.execute(httppost);
之后
TextView myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText(response);
2)在尝试之外定义
HttpResponse
响应。编辑:当您在try块外定义时指定为WindyB时,请确保
null
检查以避免NullPointerException
。阅读此link