android.os.NetworkOnMainThreadException
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
// used for interacting with user interface
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
// used for passing data
import android.os.Handler;
import android.os.Message;
// used for connectivity
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private static final String TAG = "Test";
private Button MiBoton;
private HttpResponse response;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MiBoton = (Button) findViewById(R.id.button1);
MiBoton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Log.v(TAG, "Leandro");
//HttpClient httpclient = new DefaultHttpClient();
//HttpGet httpget = new HttpGet("http://www.leandroascierto.com");
//try{
//message.setText("333");
// HttpResponse response = httpclient.execute(httpget);
//message.setText("444");
// StatusLine statusLine = response.getStatusLine();
// int statusCode = statusLine.getStatusCode();
// if(statusCode == 200){
// Log.v(TAG, "sdf");
// }else
// Log.v(TAG, "mierda");
//}catch(Exception e){
// Log.v(TAG, e.toString());
//}
try {
// Perform action on click
URL url = new URL("http://www.leandroascierto.com");
Log.v(TAG,"1");
URLConnection conn = url.openConnection();
Log.v(TAG,"2");
BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
Log.v(TAG,"3");
String line = "";
while ((line = rd.readLine()) != null) {
Message lmsg;
lmsg = new Message();
lmsg.obj = line;
lmsg.what = 0;
Log.v(TAG, lmsg.toString());
}
}
catch (Exception e) {
Log.v(TAG, e.toString());
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onStart(){
super.onStart();
//Log.v(TAG, "Leandro Ascierto");
}
}<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.helloworld.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button1"
android:layout_gravity="left|center_vertical"/>
</LinearLayout>
public static String valida(String pParametro) {
HttpURLConnection vConexion = null;
URL vDireccion;
String vResultado = "";
try {
vDireccion = new URL("http://www.prueba.com/archivo.php?pId=" + pParametro);
vConexion = (HttpURLConnection) vDireccion.openConnection();
vConexion.setConnectTimeout(2000); // Tiempo de espera de la conexion
vConexion.setReadTimeout(10000); // Tiempo de espera de la lectura del stream, si esto ocurre lanza una SocketTimeoutException
vConexion.connect();// Si no conecta lanza una SocketTimeoutException
InputStream vStream = vConexion.getInputStream();
if (vStream.available() != 0){
String vRespuesta = convertInputStreamToString(vStream);
if (vValor.equals("HOLA")) {
vResultado = "OK";
} else {
vResultado = "ERROR";
}
} else {
vResultado = "Error al leer datos del servidor."; // Conecto pero no pudo leer la respuesta (Stream).
}
vDireccion = null;
vStream.close();
vStream = null;
vConexion.disconnect();
vConexion = null;
} catch (SocketTimeoutException e) {
e.printStackTrace();
vResultado = "No se pudo Conectar al Servidor. Chequee la Conexion a Internet y vuelva a intentar.";
} catch (IOException e) {
e.printStackTrace();
vResultado = "No se pudo Conectar al Servidor. Chequee la Conexion a Internet y vuelva a intentar. 2";
}
return vResultado;
} public static String convertInputStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[500000];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}private class ThreadActualizar extends AsyncTask<String, String, String> {
Context ctx;
public ThreadActualizar(Context ctx){
this.ctx = ctx;
}
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
}
@Override
protected void onProgressUpdate(String... values) {
}
@Override
protected void onPostExecute(String result) {
}
}ThreadActualizar thrActualizar = new ThreadActualizar(this);
thrActualizar.execute("");public class CLS_HttpRequest extends Thread {
private String sURL;
private String sRespost;
public CLS_HttpRequest(String sURL) {
this.sURL = sURL;
}
public void run() {
HttpClient tHttpClient = new DefaultHttpClient();
HttpResponse tHttpResponse;
try {
tHttpResponse = tHttpClient.execute(new HttpGet(this.sURL));
StatusLine statusLine = tHttpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
tHttpResponse.getEntity().writeTo(bos);
bos.close();
this.sRespost = bos.toString();
} else {
tHttpResponse.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.fillInStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponse() {
return this.sRespost;
}
}