Httppost到php通过android无法正常工作

时间:2014-12-28 06:55:39

标签: php android android-asynctask android-logcat

mycode的

package com.example.myweb;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
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 org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.login1);
        EditText emailBox   = (EditText)findViewById(R.id.email);
        EditText passwordBox   = (EditText)findViewById(R.id.password);
        final String emailId = emailBox.getText().toString();
        final String passwordId = passwordBox.getText().toString();
        button.setOnClickListener(new Button.OnClickListener()   {             
           public void onClick(View v)  {               
            try {
                getUserLoggedIn(emailId,passwordId);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();                    
            }               
           }  
         });        
    }
    public void getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{

        HttpClient client = new DefaultHttpClient();
        HttpPost  post = new HttpPost("http://localhost/testand.php");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("email", email));
        pairs.add(new BasicNameValuePair("password", password));
        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);

        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            String responseStr = EntityUtils.toString(resEntity).trim();

            TextView textV1 = (TextView)findViewById(R.id.textV1);
            String myName = responseStr;

            textV1.setText(myName + ", Welcome to Socionet. :) ");

        }




        //JSONObject json = stringToJsonobj(response.toString());  // a is your string response



    }

    public JSONObject stringToJsonobj(String result)
    {
        JSONObject jObj = null;
            try {

            jObj = new JSONObject(result);          

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());

        }

         return jObj; 
}   
}

当我尝试运行它时会显示此错误!!

我正在尝试通过httpost向php发送数据,但它无法正常工作。 我想我需要在代码中的某个地方使用AsyncTask,但我不知道它的使用权以及使用AsyncTask的地点和方式

logcat的

12-28 06:50:59.677: W/System.err(783): android.os.NetworkOnMainThreadException
12-28 06:50:59.698: W/System.err(783):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-28 06:50:59.698: W/System.err(783):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
12-28 06:50:59.705: W/System.err(783):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
12-28 06:50:59.705: W/System.err(783):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
12-28 06:50:59.705: W/System.err(783):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-28 06:50:59.718: W/System.err(783):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-28 06:50:59.725: W/System.err(783):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-28 06:50:59.725: W/System.err(783):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-28 06:50:59.725: W/System.err(783):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-28 06:50:59.739: W/System.err(783):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-28 06:50:59.739: W/System.err(783):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-28 06:50:59.745: W/System.err(783):  at com.example.myweb.MainActivity.getUserLoggedIn(MainActivity.java:64)
12-28 06:50:59.760: W/System.err(783):  at com.example.myweb.MainActivity$1.onClick(MainActivity.java:47)
12-28 06:50:59.760: W/System.err(783):  at android.view.View.performClick(View.java:4204)
12-28 06:50:59.765: W/System.err(783):  at android.view.View$PerformClick.run(View.java:17355)
12-28 06:50:59.765: W/System.err(783):  at android.os.Handler.handleCallback(Handler.java:725)
12-28 06:50:59.775: W/System.err(783):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-28 06:50:59.805: W/System.err(783):  at android.os.Looper.loop(Looper.java:137)
12-28 06:50:59.805: W/System.err(783):  at android.app.ActivityThread.main(ActivityThread.java:5041)
12-28 06:50:59.805: W/System.err(783):  at java.lang.reflect.Method.invokeNative(Native Method)
12-28 06:50:59.815: W/System.err(783):  at java.lang.reflect.Method.invoke(Method.java:511)
12-28 06:50:59.815: W/System.err(783):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-28 06:50:59.835: W/System.err(783):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-28 06:50:59.845: W/System.err(783):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

android.os.NetworkOnMainThreadException是个例外。不要在主UI线程上运行网络操作。使用AsyncTask或Handler也是如此。

您可以在here

找到有关该主题的更多信息

答案 1 :(得分:0)

这是networkonmainthread异常...当我们尝试通过web服务(如php或c#)运行asynctask和android-Db连接时,会发生此错误....许多线程如thisthis给出它的解决方案。

之前我已完成此工作...在Oncreate()块

中添加以下代码给ur活动

if (android.os.Build.VERSION.SDK_INT > 8) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }

你不会面对错误......并且不要忘记许可

<uses-permission android:name="android.permission.INTERNET" />

有时下一个错误是没有连接,因为avg或avast阻止通过防火墙的外部连接等防病毒。禁用防病毒防火墙。