无法运行“Variable = httpClient.execute(httpPost);”在doInBackground内

时间:2014-10-29 16:23:00

标签: java android android-asynctask

为什么我无法运行" HttpResponse response = client.execute(request);"在Async方法中(doInBackground)....因为每次我运行我的代码时,我总是会在它所说的位置出现错误" HttpResponse response = client.execute(request);" .....是的,我已经包含了 - "

<小时/>
    These are the Logcat:

10-30 13:14:11.459: E/Trace(795): error opening trace file: No such file or directory (2)
10-30 13:14:11.950: D/dalvikvm(795): GC_FOR_ALLOC freed 101K, 8% free 2666K/2888K, paused 67ms, total 69ms
10-30 13:14:11.989: I/dalvikvm-heap(795): Grow heap (frag case) to 3.791MB for 1127536-byte allocation
10-30 13:14:12.110: D/dalvikvm(795): GC_FOR_ALLOC freed 2K, 6% free 3765K/3992K, paused 120ms, total 120ms
10-30 13:14:12.210: D/dalvikvm(795): GC_CONCURRENT freed <1K, 6% free 3785K/3992K, paused 10ms+7ms, total 100ms
10-30 13:14:12.489: D/libEGL(795): loaded /system/lib/egl/libEGL_emulation.so
10-30 13:14:12.489: D/(795): HostConnection::get() New Host Connection established 0x2a150a28, tid 795
10-30 13:14:12.561: D/libEGL(795): loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-30 13:14:12.570: D/libEGL(795): loaded /system/lib/egl/libGLESv2_emulation.so
10-30 13:14:12.710: W/EGL_emulation(795): eglSurfaceAttrib not implemented
10-30 13:14:12.750: D/OpenGLRenderer(795): Enabling debug mode 0
10-30 13:14:13.000: I/Choreographer(795): Skipped 39 frames!  The application may be doing too much work on its main thread.
10-30 13:14:21.529: D/dalvikvm(795): GC_CONCURRENT freed 41K, 4% free 4132K/4292K, paused 19ms+6ms, total 109ms
10-30 13:14:21.673: D/Testing(795): onCreateView(LayoutInflater inflater, viewGroup container, Bundle savedInstanceState
10-30 13:14:21.821: I/System.out(795): testing 12, testing 12
10-30 13:14:21.821: D/still inside the onCreateView()(795):  Button testButton has initialised successfully
10-30 13:14:21.821: D/.......||(795): ||.........
10-30 13:14:21.821: V/TextView sTatusComment1= (TextView)v.findViewById(R.id.textView4);(795): ...
10-30 13:14:21.821: D/sTatusComment1.setText(Please enter option(795):  success)
10-30 13:14:24.880: D/just entered(795):  onClick(View v)
10-30 13:14:24.889: D/REST_code REST_obj:(795):  initialised successfully!)
10-30 13:14:24.889: D/boolean invalidValue=true(795):  initialised successfully!)
10-30 13:14:24.909: D/int executionOtion = 99;(795):  initialised successfully!)
10-30 13:14:24.920: V/executionOption(795): 99
10-30 13:14:24.920: D/if (invalidValue==true) {(795):  successfully!)
10-30 13:14:24.920: D/try clause(795):   successfully!)
10-30 13:14:24.930: V/sTatus =(795): 3
10-30 13:14:24.930: D/......................(795):   ....................
10-30 13:14:24.930: V/executionOption(795): 3
10-30 13:14:24.930: V/executionOption =(795): 3
10-30 13:14:24.930: D/OPTION 1 BYPASSED!!(795):   successfully!)
10-30 13:14:24.930: D/executionOption == 99 else {(795): successfull
10-30 13:14:24.930: D/REST_object.oauth2Login()(795):  BANG !!!!
10-30 13:14:24.930: D/if (executionOption >=2(795):  BANG !!!  BANG !!! 
10-30 13:14:24.930: D/if (executionOption >=2(795):  BANG !!!  BANG !!! BANG  !! 
10-30 13:14:24.939: D/JUST BEFORE  new CopyOfREST_code(executionOption);(795):  TESTING 
10-30 13:14:24.949: D/INSIDE(795): public CopyOfREST_code (int executionOption2) 
10-30 13:14:24.949: D/JUST BEFORE(795): if( executionOption ==99) 
10-30 13:14:24.949: D/INSIDE(795): } else {
10-30 13:14:24.949: D/_______________ Login _______________(795): _______________ Login _______________
10-30 13:14:24.949: I/System.out(795): _______________ Login _______________
10-30 13:14:24.959: D/_______________ Login _______________(795): _______________ Login _______________
10-30 13:14:24.989: I/System.out(795): Enviado: grant_type=password&username=demo@demo.com&password=passwordTOKEN&client_id=CONSUMER_KEY&client_secret=CONSUMER_SECRET
10-30 13:14:24.989: D/BEFORE >>(795): response = httpClient.execute(httpPost);
10-30 13:14:25.081: D/AndroidRuntime(795): Shutting down VM
10-30 13:14:25.081: W/dalvikvm(795): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-30 13:14:25.129: E/AndroidRuntime(795): FATAL EXCEPTION: main
10-30 13:14:25.129: E/AndroidRuntime(795): android.os.NetworkOnMainThreadException
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
10-30 13:14:25.129: E/AndroidRuntime(795):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
10-30 13:14:25.129: E/AndroidRuntime(795):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-30 13:14:25.129: E/AndroidRuntime(795):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-30 13:14:25.129: E/AndroidRuntime(795):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-30 13:14:25.129: E/AndroidRuntime(795):  at com.example.nettec.CopyOfREST_code.oauth2Login(CopyOfREST_code.java:244)
10-30 13:14:25.129: E/AndroidRuntime(795):  at com.example.nettec.CopyOfREST_code.<init>(CopyOfREST_code.java:144)
10-30 13:14:25.129: E/AndroidRuntime(795):  at com.example.nettec.FragmentTwo.onClick(FragmentTwo.java:247)
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.view.View.performClick(View.java:4204)
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.view.View$PerformClick.run(View.java:17355)
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.os.Handler.handleCallback(Handler.java:725)
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.os.Looper.loop(Looper.java:137)
10-30 13:14:25.129: E/AndroidRuntime(795):  at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 13:14:25.129: E/AndroidRuntime(795):  at java.lang.reflect.Method.invokeNative(Native Method)
10-30 13:14:25.129: E/AndroidRuntime(795):  at java.lang.reflect.Method.invoke(Method.java:511)
10-30 13:14:25.129: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 13:14:25.129: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 13:14:25.129: E/AndroidRuntime(795):  at dalvik.system.NativeStart.main(Native Method)
10-30 13:14:25.279: D/dalvikvm(795): GC_CONCURRENT freed 141K, 6% free 4484K/4744K, paused 5ms+14ms, total 163ms



    -------------------------------------------------------------

Below  is the ASYNC CLASS CODE:

        package com.example.nettec;

        import java.io.BufferedReader;

        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.IOException;
        import java.io.UnsupportedEncodingException;

        import org.apache.http.Header;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.entity.StringEntity;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.message.BasicHeader;
        import org.apache.http.util.EntityUtils;
        import org.json.JSONException;
        import org.json.JSONObject;

        import android.util.Log;
        import android.view.View;
        import android.widget.TextView;
        import android.app.ProgressDialog;
        import android.os.AsyncTask;

            public class REST_code2 extends AsyncTask<String, String, HttpResponse >{


            //---------Credentials----------
                    //Credentials providing access to a specific Salesforce organization.
                    private static final String userName = "gelsonmascarenhas@hotmail.com"; // COPY USERNAME
                    private static final String password = "********567890iuBQsLVoX5Uhbe3vJFfjsKlEj"; // COPY PASSWORD AND TOKEN

                    //---------REST and OAuth-------
                    //Portions of the URI for REST access that are re-used throughout the code
                    private static String OAUTH_ENDPOINT = "/services/oauth2/token";
                    private static String REST_ENDPOINT = "/services/data";

                    //Holds URI returned from OAuth call, which is then used throughout the code.
                    String baseUri;

                    //The oauthHeader set in the oauth2Login method, and then added to
                    //each HTTP object that is used to invoke the REST API.
                    Header oauthHeader;

                    //Basic header information added to each HTTP object that is used
                    //to invoke the REST API.
                    Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");

                    //----------Data specific---------
                    //Retrieved accountId that is used when contact is added.
                    private static String accountId;

                    //Id of inserted contact. Used to update contact.
                    private static String contactId;

                    //----------Utility-------------
                    //Used to get input from console.
                    private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));



                    ProgressDialog dialog;
                    private View host; //view to be initialised on the constructor of this class
                    TextView sTatusComment1;


                    /* Frament variable identifiers */
                    private static Boolean authentication;
                    private static int executionChoice;





                    //........TO BE DELETED ...........//
                    View view_inflater_const;



                    /**
                     * This class holds all the values related to the credentials needed to
                     * make the OAuth2 request for authentication. Normally they would not be set in
                     * this manner.
                     */ 
                    class UserCredentials {
                        String loginInstanceDomain = "na15.salesforce.com"; // COPY YOUR SERVER INSTANCE
                        String apiVersion = "27"; // COPY YOU API VERSION
                        String userName = REST_code2.userName;
                        String password = REST_code2.password;
                        String consumerKey = "3MVG9A2kN3Bn17htllMZ507EvCBOeX8Qfq6sV5vA3HZs6MVowf7CB04msHqmdkXHrYEVsdciASN8Uoz2cj.U."; // COPY YOUR CONSUMER KEY     
                        String consumerSecret = "3783326479037458971"; // COPY YOUR CONSUMER SECRET
                        String grantType = "password";
                    }

                    /**
                     * Constructor drives console interaction and calls appropriate methods.
                     */
                    public REST_code2(View host) {

                        //showMenu();//             FragmentTwo Invoke

                        this.host = host; // host is variable of type View


                    }


                    protected void SetStatusCommand(int executionOption ){


                        executionChoice= executionOption;


                    }

                    protected void setAuthentication(boolean A){
                        authentication = A;
                    }

                    protected int getexecutionChoice(){
                        return executionChoice;
                    }


                    protected boolean getauthenticationStat(){
                        return authentication;//boolean
                    }

                    /**
                     * This method connects the program to the Salesforce organization using OAuth. 
                     * It stores returned values for further access to organization.
                     * @param userCredentials Contains all credentials necessary for login
                     * @return
                     */

                        @Override
                    protected void onPreExecute() {

                            // TODO Auto-generated method stub
                        super.onPreExecute();   


                        }

                        @Override/
                        protected HttpResponse doInBackground(String ... params){

                            OAuth2Response oauth2Response = null;
                            HttpResponse response = null;
                            UserCredentials userCredentials = new UserCredentials();
                            String loginHostUri = "https://" + userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;


                        if(getauthenticationStat()==false)
                                {


                                try {
                                    //Construct the objects for making the request
                                    HttpClient httpClient = new DefaultHttpClient();
                                    HttpPost httpPost = new HttpPost(loginHostUri);
                                    StringBuffer requestBodyText = new StringBuffer("grant_type=password");
                                    requestBodyText.append("&username=");
                                    requestBodyText.append(userCredentials.userName);
                                    requestBodyText.append("&password=");
                                    requestBodyText.append(userCredentials.password);
                                    requestBodyText.append("&client_id=");
                                    requestBodyText.append(userCredentials.consumerKey);
                                    requestBodyText.append("&client_secret=");
                                    requestBodyText.append(userCredentials.consumerSecret);
                                    Log.d("Enviado: ", requestBodyText.toString());
                                    ///////System.out.println("Enviado: "+requestBodyText.toString());
                                    StringEntity requestBody = new StringEntity(requestBodyText.toString());
                                    Log.d("StringEntity requestBody = new StringEntity(requestBodyText.toString()); ", requestBodyText.toString());
                                    requestBody.setContentType("application/x-www-form-urlencoded");
                                    Log.d("requestBody.setContentType( ", "application/x-www-form-urlencoded");
                                    httpPost.setEntity(requestBody);
                                    Log.d("httpPost.setEntity(requestBody); ", "<-------");
                                    httpPost.addHeader(prettyPrintHeader);
                                    Log.d("httpPost.addHeader(prettyPrintHeader); ", "<-------");

                                                                                            response = httpClient.execute(httpPost);


                                                if (  response.getStatusLine().getStatusCode() == 200 ) {
                                                Log.d("if (  response.getStatusLine().getStatusCode() == 200 ) {", "<--------");
                                                String response_string = EntityUtils.toString(response.getEntity());
                                                Log.d("String response_string =", "EntityUtils.toString(response.getEntity());");

                                                    try {
                                                        Log.d("entered try{", "<--------");
                                                        JSONObject json = new JSONObject(response_string);
                                                        oauth2Response = new OAuth2Response(json);
                                                        Log.d("JSON returned by response +/n: ",  json.toString(1));
                                                        publishProgress("JSON returned by response +/n: ",  json.toString(1));

                                                        //System.out.println("JSON returned by response: +\n" + json.toString(1));
                                                        } catch (JSONException je) {
                                                            je.printStackTrace();
                                                        }  
                                            baseUri = oauth2Response.instance_url + REST_ENDPOINT + "/v" + userCredentials.apiVersion +".0";
                                            oauthHeader = new BasicHeader("Authorization", "OAuth " + oauth2Response.access_token);
                                            Log.d("\nSuccessfully logged in to instance: " , baseUri );
                                                                                } 
                                            else {
                                                Log.d("An error has occured. Http status: " , "there is suppost to be an int variable, go and check");


                                            //System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode()); //@+id/textView4
                                                //System.out.println(getBody(response.getEntity().getContent())); //@+id/textView4
                                                System.exit(-1);
                                                }
                                }  /*end of try */
                        catch (UnsupportedEncodingException uee) {
                            uee.printStackTrace();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        } catch (NullPointerException npe) {
                            npe.printStackTrace();
                        }
                                }

                            return response;    }

    CODE THAT INVOKES THE ASYNC I had to remove all the imports in this class to save charater cout space:

        package com.example.nettec; 


    public class FragmentTwo extends Fragment implements View.OnClickListener{ 

        View view_inflater_const;
        ViewGroup container_const;
        Bundle savedInstanceState_const;


        private static String accountId="empty";


        private static String contactId;


         ImageView ivIcon; 
         TextView tvItemName; 
         Button Button_Ok;

         View GlobalView;

         EditText sTatus;
         String String_sTatus;
         TextView sTatusComment1;


         public static final String IMAGE_RESOURCE_ID = "iconResourceID"; 
         public static final String ITEM_NAME = "itemName"; 

         public static final String BUTTON_OK = "button_OK";


         public View RetrieveView(){
             return GlobalView;
         }

         public void storeView(View v){
             GlobalView= v;
         }


         public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                     Bundle savedInstanceState) { 
             Log.d("Testing", "onCreateView(LayoutInflater inflater, viewGroup container, Bundle savedInstanceState");

               View view = inflater.inflate(R.layout.fragment_layout_two, container, 
                       false); 

               storeView(view);

               Button testButton = (Button) view.findViewById(R.id.button1);


               Log.d("still inside the onCreateView()", " Button testButton has initialised successfully");


            sTatusComment1= (TextView) view.findViewById(R.id.textView4);


            Log.v("TextView sTatusComment1= (TextView)v.findViewById(R.id.textView4); ",(String)sTatusComment1.getText().toString());


            sTatusComment1.setText("Please enter option :");
            Log.d("sTatusComment1.setText(Please enter option "," success)");

              testButton.setOnClickListener(this);




               ivIcon=(ImageView)view.findViewById(R.id.frag2_icon); 
               tvItemName = (TextView) view.findViewById(R.id.frag2_text);


               tvItemName.setText(getArguments().getString(ITEM_NAME)); 
               ivIcon.setImageDrawable(view.getResources().getDrawable( 
                       getArguments().getInt(IMAGE_RESOURCE_ID))); 




               return view; 
         }


         public void  onActivityCreated(Bundle savedInstanceState){

             super.onActivityCreated(savedInstanceState);

             sTatusComment1= (TextView) getActivity().findViewById(R.id.textView1);

         }

         public void changeText(String data){
             sTatusComment1.setText(data);
         }





         @Override
            public void onClick(View v) {


             Log.d("just entered"," onClick(View v)");

            v=RetrieveView();

             REST_code REST_obj = new REST_code(v);
             REST_code2 REST_obj2 = new REST_code2(v);


             sTatus= (EditText) v.findViewById(R.id.editText1);
             Log.d("REST_code REST_obj: "," initialised successfully!)");

                boolean invalidValue = true;
                Log.d("boolean invalidValue=true "," initialised successfully!)");
                int executionOption=99;


                if (invalidValue==true) {
                    Log.d("if (invalidValue==true) { "," successfully!)");
                    try {
                        Log.d("try clause ","  successfully!)");
                        String quickVar = sTatus.getText().toString();
                        Log.v("sTatus = ",quickVar);///THERE IS SOMETHING WRONG WITH THIS

                     sTatus = (EditText)v.findViewById(R.id.editText1);//pass the value of editText1 to var sTatus String




                     executionOption = Integer.parseInt(sTatus.getText().toString()); //convert the var sTatus string to int and assign to executionOption var
                     Log.v("executionOption ",String.valueOf(executionOption));
                     String quickcheck= (String)sTatus.getText().toString();
                     Log.v("executionOption = ",quickcheck);
                     if ((executionOption < 1 || executionOption > 4) && executionOption!=99) {
                         Log.d("inside if ((executionOption <1 || ","executionOption > 4) && executionOption!=99");
                            Log.d("Please enter ", " 1, 2, 3, 4, or 99.\n"); //@+id/textView2
                            sTatusComment1.setText("Enter the number of the sample to run: ");//variable that will hold answer      @+id/editText1  --FragmentTwo invoke
                            refresh_frag();     //FragmentTwo Invoke
                        } else {
                            Log.d(" OPTION 1 BYPASSED!! " , "  successfully!)");
                            invalidValue = false;
                        }
                    } 
                    catch (Exception e) {
                        Log.d("catch (Exception e) {"," initialised successfully!)");

                        sTatusComment1.setText("Enter the number of the sample to run: ");              // @+id/editText1

                    }           
                }
                if (executionOption == 99) {
                     Log.d("if (executionOption ==99 ",") { successful");
                    sTatusComment1.setText("No action taken");//@+id/textView4
                } else {
                    //NO CODE YET

                    if (executionOption >= 2) {
                    //NO CODE YET   

                    }



                     if (executionOption >= 3) {

                        Log.v("inside executionOption ", ">=3 ");

                        if (accountId != null) {


                            //new CopyOfREST_code(executionOption);
                            REST_obj2.execute();
                            //REST_obj.execute();


                        } else {

                        }
                                                }
                     if (executionOption == 4) {
                        if (contactId != null) {
                            new CopyOfREST_code(executionOption);
                            //REST_obj.restPatchExample(contactId);
                        }  else {
                            sTatusComment1.setText("contact not found");
                        }
                    }   
                }   



           }

    }

1 个答案:

答案 0 :(得分:0)

您的logcat显示您实际使用的代码中的 CopyOfREST_code.java(您似乎从未发布过)您正在执行网络操作(特别是对{{1的调用) }})在初始化程序中。

虽然AsyncTask的oauth2Login()方法在UI线程上运行,但是类的初始化在UI线程上运行,这意味着您无法在那里进行网络操作。

doInBackground()

中移动网络操作的全部