Android方法不执行httppost请求

时间:2015-03-11 12:19:10

标签: android exception post httpresponse

我必须做一个http帖子来获取一个令牌,这将授予我使用我的应用程序的权限。 方法(obtieneToken)将此标记获取到另一个方法旁边的Asyntask类中。从另一个没有异步的类调用此方法,该类从App活动调用。 当我的函数到达httpClient.execute(post)时,索引转到异常。 我比较了我的应用程序与我的Web应用程序,Web应用程序运行良好。下一步是使用Wireshark捕获并且...当我执行我的应用程序时,我的wlan界面没有收到来自应用程序的任何请求。哪个可能是问题? 这是代码:

public class ObtencionDatosUsuario extends AsyncTask<Integer, Integer, Boolean> {


protected static User obtieneDatos(String url, String aut) {
    // TODO Auto-generated method stub
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet del = new HttpGet(url);// Se obtienen
                                                            // los datos de
                                                            // la url del
                                                            // usuario
    del.setHeader("content-type", "application/json");
    del.setHeader("X-Auth-Token",aut);// contenidoToken es el string que se obtiene de la respuesta del token
    User usuario = new User();
    try {
        HttpResponse resp = httpClient.execute(del);
        StatusLine estatus = resp.getStatusLine();
        if (estatus.getStatusCode() == 200) {
            InputStream is= null;
            is = resp.getEntity().getContent();
            usuario =(User) HalUnmarshaller.unmarshal(is, User.class);
        } else {
            System.out.println("Error");
            usuario= null;
        }

    } catch (Exception ex) {
        Log.e("ServicioRest", "Error!", ex);
    }
    return usuario;
}

protected static List<User> obtieneAmigos(String url, String aut) {
    // TODO Auto-generated method stub
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet del = new HttpGet(url);// Se obtienen los datos de la url del
                                    // usuario
    del.setHeader("content-type", "application/json");
    del.setHeader("X-Auth-Token", aut);
    List<User> friends = null;
        HttpResponse resp;
        try {
            resp = httpClient.execute(del);
            StatusLine estatus = resp.getStatusLine();
            if(estatus.getStatusCode()==200){
                InputStream is= null;
                is = resp.getEntity().getContent();
                friends= (List<User>) HalUnmarshaller.unmarshal(is, User.class);
                return friends;
            }else{
                friends= null;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    return friends;
}

protected static List<GroupEvent> obtieneEventos(String url, String aut) {
    // TODO Auto-generated method stub
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet del = new HttpGet(url); // Se obtienen los datos de la url del usuario
    del.setHeader("content-type", "application/json");
    del.setHeader("X-Auth-Token",aut);
    List<GroupEvent> eventos = null;
        HttpResponse resp;
        try {
            resp = httpClient.execute(del);
            StatusLine estatus = resp.getStatusLine();
            if(estatus.getStatusCode() == 200){
                InputStream is= null;
                is= resp.getEntity().getContent();
                eventos = (List<GroupEvent>) HalUnmarshaller.unmarshal(is, GroupEvent.class);

            }else{
                eventos= null;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return eventos;

}
//getToken 
protected static AuthToken obtieneToken(String nombre, String clave, String url){
    // TODO Auto-generated method stub
    AuthToken token= new AuthToken();
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);// Solicitud token
    int code;
    String aut=nombre+":"+clave;
    String conectionValue;
    String codificada= Base64.encodeToString(aut.getBytes(), 0);
    String coded= codificada.replace("\n", "");
    System.out.println("nombre:clave= "+aut+" codificado es= "+coded);
    post.setHeader("content-type", "application/json");
    post.setHeader("Authorization", "Basic "+coded);
    try {
        HttpResponse resp = httpClient.execute(post);//Genera una excepcion 
        InputStream is= resp.getEntity().getContent();
        if((code=resp.getStatusLine().getStatusCode())!=200){
            token.setAuthToken("0");


        }else{
        token= (AuthToken) HalUnmarshaller.unmarshal(is, AuthToken.class);
        System.out.println("Token recibido en obtencion: "+ token);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {//Excepcion lanzad a por el post
        // TODO Auto-generated catch block
        e.printStackTrace(); 
    }

    return token;
}
@Override
protected Boolean doInBackground(Integer... params) {
    // TODO Auto-generated method stub
    return null;
}

}

这是包含异步方法的调用者的类:

public class ObtieneRecursos {
static String ip= "192.168.0.15";
public static User obtieneDatosUsuario(String aut, String who){
    //Peticion get a /users/:id
    String url= "http://"+ip+":8080/api/users/"+who;
    User usuario= new User();
    usuario= ObtencionDatosUsuario.obtieneDatos(url,aut);

    return usuario;
}
public static AuthToken obtieneTokenMe(String nombre, String clave){
    String url= "http://"+ip+":8080/api/auth-tokens/";
    AuthToken token= new AuthToken();
    token= ObtencionDatosUsuario.obtieneToken(nombre, clave, url);
    return token;
   }
}

非常感谢。

编辑:记录

03-11 13:31:39.272: I/ViewRootImpl(522): ViewRoot's Touch Event : Touch Down
03-11 13:31:39.312: I/ViewRootImpl(522): ViewRoot's Touch Event : Touch UP
03-11 13:31:46.472: I/System.out(522): Recibido mik.xx@gmail.com|xx
03-11 13:31:46.562: I/System.out(522): nombre:clave= mik.xx@gmail.com:xx codificado es= bWlrLmNvcmN1ZXJhQGdtYWlsLmNvbTpjb3JjdWVyYTkx

03-11 13:31:48.632: E/DataScheduler(522): isDataSchedulerEnabled():false

03-11 13:31:48.632: W/System.err(522): android.os.NetworkOnMainThreadException
03-11 13:31:48.642: W/System.err(522):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1148)
03-11 13:31:48.642: W/System.err(522):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-11 13:31:48.642: W/System.err(522):  at libcore.io.IoBridge.connectErrno(IoBridge.java:176)
03-11 13:31:48.642: W/System.err(522):  at libcore.io.IoBridge.connect(IoBridge.java:128)
03-11 13:31:48.642: W/System.err(522):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-11 13:31:48.642: W/System.err(522):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
03-11 13:31:48.642: W/System.err(522):  at java.net.Socket.connect(Socket.java:833)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-11 13:31:48.642: W/System.err(522):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-11 13:31:48.642: W/System.err(522):  at com.example.modelo.ObtencionDatosUsuario.obtieneToken(ObtencionDatosUsuario.java:144)
03-11 13:31:48.642: W/System.err(522):  at com.example.modelo.ObtieneRecursos.obtieneTokenMe(ObtieneRecursos.java:27)
03-11 13:31:48.652: W/System.err(522):  at com.example.pestanasholacampus.InitActivity.compruebaUsuario(InitActivity.java:122)
03-11 13:31:48.652: W/System.err(522):  at com.example.pestanasholacampus.InitActivity$2.onClick(InitActivity.java:68)
03-11 13:31:48.652: W/System.err(522):  at android.view.View.performClick(View.java:4442)
03-11 13:31:48.652: W/System.err(522):  at android.view.View$PerformClick.run(View.java:18473)
03-11 13:31:48.652: W/System.err(522):  at android.os.Handler.handleCallback(Handler.java:733)
03-11 13:31:48.652: W/System.err(522):  at android.os.Handler.dispatchMessage(Handler.java:95)
03-11 13:31:48.652: W/System.err(522):  at android.os.Looper.loop(Looper.java:136)
03-11 13:31:48.652: W/System.err(522):  at android.app.ActivityThread.main(ActivityThread.java:5105)
03-11 13:31:48.652: W/System.err(522):  at java.lang.reflect.Method.invokeNative(Native Method)
03-11 13:31:48.652: W/System.err(522):  at java.lang.reflect.Method.invoke(Method.java:515)
03-11 13:31:48.652: W/System.err(522):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
03-11 13:31:48.652: W/System.err(522):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
03-11 13:31:48.652: W/System.err(522):  at dalvik.system.NativeStart.main(Native Method)

编辑2:现在我有从普通类调用的doInBackground方法中的代码:

public class ObtencionTokenUsuario extends AsyncTask<String, Integer, AuthToken> {

@Override
protected AuthToken doInBackground(String... datos) {
    // TODO Auto-generated method stub
            AuthToken token= new AuthToken();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(datos[2]);// Solicitud token
            int code;
            String aut=datos[0]+":"+datos[1];
            String conectionValue;
            String codificada= Base64.encodeToString(aut.getBytes(), 0);
            String coded= codificada.replace("\n", "");
            System.out.println("nombre:clave= "+aut+" codificado es= "+coded);
            post.setHeader("content-type", "application/json");
            post.setHeader("Authorization", "Basic "+coded);
            try {
                HttpResponse resp = httpClient.execute(post);//Genera una excepcion 
                InputStream is= resp.getEntity().getContent();
                if((code=resp.getStatusLine().getStatusCode())!=200){
                    token.setAuthToken("0");


                }else{
                token= (AuthToken) HalUnmarshaller.unmarshal(is, AuthToken.class);
                System.out.println("Token recibido en obtencion: "+ token);
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {//Excepcion lanzad a por el post
                // TODO Auto-generated catch block
                e.printStackTrace(); 
            }

            return token;
}

}

上课:

public class ObtieneRecursos{
public static AuthToken obtieneTokenMe(String nombre, String clave){
    String url= "http://"+ip+":8080/api/auth-tokens/";
    String[] params= new String[3];
    params[0]=nombre;
    params[1]=clave;
    params[2]=url;
    System.out.println("nombre = "+params[0]);
    System.out.println("clave = "+params[1]);
    System.out.println("url = "+params[2]);
    AuthToken token= new AuthToken();
    ObtencionTokenUsuario du= new ObtencionTokenUsuario();
    token=du.doInBackground(params);
    return token;
}
}

1 个答案:

答案 0 :(得分:0)

解决。问题出在HttpPost上,它收到的是String而不是URI。