public class TestProjMain extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
tView.setText("");
// Perform action on click
URL url = new URL(/*"http://www.google.com"*/eText.getText().toString());
URLConnection conn = url.openConnection();
// Get the response
开发者_如何学Python BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
tView.append(line);
}
}
catch (Exception e) {
}
}
});
}
}
I wrote this but its not working. I also used the httpclient code but that was also not working. My emulator stops responding every time whenever I execute this function. I don't know where the problem is?? somebody please help !! thanks in advance...
Its better to use AsyncTask to make a web call.
Use the methods of AsyncTask as follows:
In doInBackground() method, write your below code:
URL url = new URL(/*"http://www.google.com"*/eText.getText().toString()); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = "";
In onPostExecute() method, write your display code:
while ((line = rd.readLine()) != null) { tView.append(line); }
Use an asynctask like so
public class RetrieveSiteData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
StringBuilder builder = new StringBuilder(16384);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
builder.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
@Override
protected void onPostExecute(String result) {
}
}
精彩评论