我正在尝试添加getByName以获取主机名的IP地址,并在我的POST命令中使用它
问题是无论我在哪里插入此代码,它都会崩溃
我试图在doInBackground中插入它也会崩溃,所以我应该在哪里插入它?

package com.example.loginad;



import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;







import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logindb);

        login=(Button)findViewById(R.id.login);
        u=(EditText)findViewById(R.id.u);
        p=(EditText)findViewById(R.id.p);
        res=(TextView)findViewById(R.id.res);
        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());


            }
        });



    }
    private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            boolean success = postData(params[0],params[1]);
             try
          {
                 InetAddress address=null;
           address = InetAddress.getByName("Nicky-PC");
                host=address.getHostAddress();
          }
          catch(Exception e)
          {
             e.printStackTrace();
          }
            return success;
        }

        protected void onPostExecute(Boolean localres){

             if (localres){
                    res.setText("A Correct Username and Password");
                }else{
                    res.setText("Incorrect Username or Password");
                }
                Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            //pb.setProgress(progress[0]);
            //Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();

        }
        /*public void ObtainHost()
        {
            try
            {

            }
            catch(Exception e)
            {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            }

        } */

        public Boolean postData(String a,String b) {
              ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
              postParameters.add(new BasicNameValuePair("username", a));
              postParameters.add(new BasicNameValuePair("password", b));
              postParameters.add(new BasicNameValuePair("mobileid",x));
              // String valid = "1";
              String response = null;
              try {


                //  Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
                 response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.
   result = response.toString();
                  // res = res.trim();
                  result = result.replaceAll("\\s+", "");
                  // error.setText(res);

              } catch (Exception e) {
                  res.setText(e.toString());
              }

           return result.equals("1");

        }



    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.logindb, menu);
        return true;
    }

}


堆栈跟踪

11-26 21:28:37.856: D/libEGL(17150): loaded /system/lib/egl/libEGL_genymotion.so
11-26 21:28:37.876: D/(17150): HostConnection::get() New Host Connection established 0xb8ed35a8, tid 17150
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv2_genymotion.so
11-26 21:28:37.968: W/EGL_genymotion(17150): eglSurfaceAttrib not implemented
11-26 21:28:37.976: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from GradienCache
11-26 21:28:37.996: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-26 21:28:37.996: D/OpenGLRenderer(17150): Enabling debug mode 0
11-26 21:28:44.876: W/dalvikvm(17150): threadid=13: thread exiting with uncaught exception (group=0xa4c1f648)
11-26 21:28:44.920: E/AndroidRuntime(17150): FATAL EXCEPTION: AsyncTask #3
11-26 21:28:44.920: E/AndroidRuntime(17150): java.lang.RuntimeException: An error occured while executing doInBackground()
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.lang.Thread.run(Thread.java:841)
11-26 21:28:44.920: E/AndroidRuntime(17150): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:837)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:358)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.checkForRelayout(TextView.java:6524)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.setText(TextView.java:3771)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.setText(TextView.java:3629)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.setText(TextView.java:3604)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:70)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:1)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-26 21:28:44.920: E/AndroidRuntime(17150):    ... 4 more
11-26 21:28:44.932: D/dalvikvm(17150): GC_FOR_ALLOC freed 259K, 5% free 6365K/6660K, paused 8ms, total 8ms

最佳答案

首先,如果要使用AsyncHttpClient,则不需要AsyncTask,但如果要使用HttpClient,则需要AsyncTask任务。
下面的代码是执行get和post请求的工作代码的一部分。根据需要进行修改

    @Override
protected String doInBackground(String... params) {
    backGroundExecuted = false;
    Log.d("doInBackground", "Start processing doInBackground");

    HttpClient httpClient = null;
    HttpPost httpPost = null;
    HttpGet httpGet = null;


     if (httpMethodType == null || url == null) {
         Log.d("doInBackground" , "The URL and Method Type is mandatory, cannot be null - httpMethodType =" + httpMethodType + " and url =" + url);
         this.getApiResponse().setSuccess(false);
         this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
         this.getApiResponse().setResponseDescription("The URL and Method Type is mandatory, cannot be null");
         return null;
     }

    try {

         //set timeout
         HttpParams httpParameters = new BasicHttpParams();
         HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
         HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);

         httpClient = new DefaultHttpClient(httpParameters);
         HttpResponse httpResponse = null;

        if (httpMethodType.equals(HTTPMethodType.POST.toString())) {
            httpPost = new HttpPost(url);
            //setting json object to request.
            if (postParams != null) {
                AbstractHttpEntity entity = null;
                entity = new ByteArrayEntity(postParams.getBytes("UTF8"));
                if (httpContentType != null) {
                    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, httpContentType));
                }
                httpPost.setEntity(entity);
            }
            httpResponse = httpClient.execute(httpPost);

        } else  if (httpMethodType.equals(HTTPMethodType.GET.toString()) || httpMethodType.equals(HTTPMethodType.PUT.toString())) {
            if (queryParams != null) {
                url = url + "?" + URLEncodedUtils.format(queryParams, "utf-8");
                Log.d(TAG ,"new URL :" + url);
            }
            httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
        }

        this.getApiResponse().setResponseCode(httpResponse.getStatusLine().getStatusCode());
        this.getApiResponse().setResponseDescription(httpResponse.getStatusLine().getReasonPhrase());
         if (this.getApiResponse().getResponseCode() != HttpStatus.SC_OK) {
             this.getApiResponse().setSuccess(false);
             Log.w(getClass().getSimpleName(),
                 "Error " + this.getApiResponse().getResponseCode() + " for URL " + url);
             Log.w(getClass().getSimpleName(),
                     "Error " +  this.getApiResponse().getResponseDescription() + " for URL " + url);
          }

         Log.d("doInBackground", "The API call executed and will check the response");
         HttpEntity entityResp = httpResponse.getEntity();
         if (entityResp != null) {
             this.getApiResponse().setResponse(appHelper.getStringFromInputStream(entityResp.getContent()));
             Log.d("doInBackground","The response is :" + this.getApiResponse().getResponse());
             this.getApiResponse().setSuccess(true);
         }

     } catch (UnsupportedEncodingException e1) {
         Log.e("doInBackground","Exception :" + e1.toString());
         this.getApiResponse().setSuccess(false);
         this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
         this.getApiResponse().setResponseDescription("Exception :" + e1.toString());
            Log.e("doInBackground","Exception :" + e1.toString());
            e1.printStackTrace();
     } catch (Exception e) {
         Log.e("doInBackground","Exception :" + e.toString());
         this.getApiResponse().setSuccess(false);
         this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
         this.getApiResponse().setResponseDescription("Exception :" + e.toString());
         if (httpPost != null && !httpPost.isAborted()) {
             httpPost.abort();
         }
     } finally {
         if (httpClient != null) {
             httpClient.getConnectionManager().shutdown();
         }
         backGroundExecuted = true;

     }
    return null;
}

09-04 08:50