I am trying to contact an API and get the response. As part of my debugging I want to insure that the response is being recorded, it should be an xml response.
Here’s what I have:
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);
}
}
I’m trying to see the response that I get, however the variable response in the line
myTextView.setText(response)
is throwing an error:
response cannot be resolved to a variable
is response not truly a variable of the type httpresponse? what’s going on here…?
Scope of the response variable is inside try block only. Two ways to resolve this:
1) Move these statements right after
HttpResponse response = httpclient.execute(httppost);2) Define
HttpResponseresponse out side the try.EDIT: As WindyB specified when you define outside the try block make sure
nullcheck to avoidNullPointerException.Read this link