Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android方法不执行httppost请求_Android_Exception_Post_Httpresponse - Fatal编程技术网

Android方法不执行httppost请求

Android方法不执行httppost请求,android,exception,post,httpresponse,Android,Exception,Post,Httpresponse,我必须做一个http帖子来获取一个令牌,这将给我使用我的应用程序的权限。 获取此标记的MethodObsientOken将其放入Asyntask类中,并与其他方法一起使用。此方法是从另一个类调用的,该类不是从应用程序活动调用的异步类。 当my函数到达httpClient.executepost时,索引转到异常。 我将我的应用程序与我的web应用程序进行了比较,web应用程序运行良好。下一步是用Wireshark和。。。当我执行我的应用程序时,我的wlan接口不会收到来自该应用程序的任何请求。哪一

我必须做一个http帖子来获取一个令牌,这将给我使用我的应用程序的权限。 获取此标记的MethodObsientOken将其放入Asyntask类中,并与其他方法一起使用。此方法是从另一个类调用的,该类不是从应用程序活动调用的异步类。 当my函数到达httpClient.executepost时,索引转到异常。 我将我的应用程序与我的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;
}
非常感谢

编辑:日志

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;
}

解决了。问题出在HttpPost上,它收到的是字符串而不是URI。

您是否将internet权限添加到清单文件中?我仍然犯这个错误是的,我有这行:你能发布你的错误日志吗?这可能有助于理解错误。您是否阅读过asynctask的文档,您在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;
}
}