Reputation: 1
first of all I have to say that I'm a beginner in Android programing and not very experienced in general programing at all. But now I decided to make a little app for my private use.
In my app I need to get some Text from a given URL into a string. I found some methods on the web and personalized them a bit. But there is something wrong because when I run the app with the Android Eclipse emulator it says "Unfortunately, xxx_app has stopped.".
Here is my code:
public String getURLtext(String zielurl) throws IllegalStateException, IOException{
String meineurl = zielurl;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(meineurl);
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
return result;
}
And this is the method where I want to show the output string in my EditText text1.
public void test(View view) throws InterruptedException, ExecutionException, IllegalStateException, IOException {
EditText text1 = (EditText)findViewById(R.id.textfeld);
String teststring = getURLtext("http://ephemeraltech.com/demo/android_tutorial20.php");
text1.setText(teststring);
}
I would be happy if anyone can help me with this.
Thanks!
Upvotes: 0
Views: 2258
Reputation: 4899
Your code looks good until you get the HTTPResponse, the bottom part (response to string) can be optimized a lot. It's also worth noticing that Android won't let you to do network operation on the main thread, so please consider using an AsyncTask to execute your http GET operation.
public String getURLtext(String zielurl) throws IllegalStateException, IOException
{
String result = ""; // default empty string
try
{
String meineurl = zielurl;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(meineurl);
HttpResponse response = httpClient.execute(httpGet, localContext);
InputStream is = response.getEntity().getContent();
result = inputStreamToString(is).toString();
}
catch (Exception ex)
{
// do some Log.e here
}
finally
{
return result;
}
}
// Fast Implementation
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return full string
return total;
}
Upvotes: 1