I'm trying to use a simple HTTP get to load a string from a webpage. However, when I run the app in the emulator, I get a strict policy violation, and nothing is displayed. The policy violation is listed as "policy=31 violation=4". If I add a permitNetwork() into the ThreadPolicy initialization, the LogCat tells me that google.com doesn't resolve to an address. Clearly, I'm missing something, but I was under the impression that this is how I should be handling network operations.
EDIT: I've altered my HttpExampleActivity.java, I now have this:
package com.android.httpexample;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;
import android.widget.TextView;
public class HttpExampleActivity extends Activity {
TextView httpStuff;
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new Builder().detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new Runnable() {
public void run() {
httpStuff = (TextView) findViewById(R.id.tvHttp);
httpStuff.post(new Runnable(){
public void run(){
GetProcedure test = new GetProcedure();
String returned;
try{
returned = test.getInternetData();
httpStuff.setText(returned);
} catch(Exception e){
e.printStackTrace();
}
}
});
}
}).start();
}
}
In my GetProcedure.java, I have this:
package com.android.httpexample;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class GetProcedure {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://google.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) != null)
{
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if(in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}