android不发送HTTP POST请求

时间:2015-04-02 05:30:40

标签: java android apache xmlhttprequest

我想从android发布到我的PHP页面,我遇到了一些问题。我阅读了很多arcticles,并使代码吼叫。单击按钮不会给出任何结果,数据不会更改。所以,你可以在我错误的地方帮助我。

package ktl.myapplication;

import java.io.IOException;
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.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    Button btnOk;
    /**Вызывается при первом создании */
    @Override
    public void onCreate(Bundle savedInstanceState)
    { super.onCreate(savedInstanceState);
        // загрузка layout
        setContentView(R.layout.activity_main);
        btnOk = (Button) findViewById(R.id.btn1);

        OnClickListener oclBtnOk = new OnClickListener() {
            @Override
            public void onClick(View v) {

                class RequestTask extends AsyncTask<String, String, String> {

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

                        try {
                            //создаем запрос на сервер
                            DefaultHttpClient hc = new DefaultHttpClient();
                            ResponseHandler<String> res = new BasicResponseHandler();

                            //он у нас будет посылать post запрос
                            HttpPost postMethod = new HttpPost("http://shkz3.info/switch.php");
                            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                            nameValuePairs.add(new BasicNameValuePair("PAR", "SVET1"));
                            //собераем их вместе и посылаем на сервер
                            postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        } catch (Exception e) {
                            System.out.println("Exp=" + e);
                        }
                        return null;
                    }
                }
            }
        };
        btnOk.setOnClickListener(oclBtnOk);
    }

}

和logcat

04-02 11:23:44.575  32216-32216/ktl.myapplication D/dalvikvm﹕ Zygote::ForkAndSpecialize : 0
04-02 11:23:44.578  32216-32216/ktl.myapplication D/dalvikvm﹕ zygote get new systemTid : 32216
04-02 11:23:44.578  32216-32216/ktl.myapplication D/dalvikvm﹕ Late-enabling CheckJNI
04-02 11:23:44.578  32216-32220/ktl.myapplication D/dalvikvm﹕ threadid=2: interp stack at 0x5ba49000
04-02 11:23:44.578  32216-32220/ktl.myapplication D/dalvikvm﹕ init ref table
04-02 11:23:44.578  32216-32220/ktl.myapplication D/dalvikvm﹕ init mutex
04-02 11:23:44.579  32216-32221/ktl.myapplication D/dalvikvm﹕ threadid=3: interp stack at 0x5bb69000
04-02 11:23:44.579  32216-32221/ktl.myapplication D/dalvikvm﹕ init ref table
04-02 11:23:44.579  32216-32221/ktl.myapplication D/dalvikvm﹕ init mutex
04-02 11:23:44.579  32216-32221/ktl.myapplication D/dalvikvm﹕ Elevating priority from 0 to -8
04-02 11:23:44.579  32216-32216/ktl.myapplication D/jdwp﹕ prepping for JDWP over ADB
04-02 11:23:44.579  32216-32222/ktl.myapplication D/dalvikvm﹕ threadid=4: interp stack at 0x5ecaa000
04-02 11:23:44.579  32216-32222/ktl.myapplication D/dalvikvm﹕ init ref table
04-02 11:23:44.579  32216-32222/ktl.myapplication D/dalvikvm﹕ init mutex
04-02 11:23:44.579  32216-32222/ktl.myapplication D/jdwp﹕ JDWP: thread running
04-02 11:23:44.580  32216-32222/ktl.myapplication D/jdwp﹕ trying to receive file descriptor from ADB
04-02 11:23:44.625  32216-32228/ktl.myapplication D/dalvikvm﹕ threadid=9: interp stack at 0x5f43e000
04-02 11:23:44.625  32216-32228/ktl.myapplication D/dalvikvm﹕ init ref table
04-02 11:23:44.625  32216-32228/ktl.myapplication D/dalvikvm﹕ init mutex
04-02 11:23:44.625  32216-32229/ktl.myapplication D/dalvikvm﹕ threadid=10: interp stack at 0x5f55c000
04-02 11:23:44.625  32216-32229/ktl.myapplication D/dalvikvm﹕ init ref table
04-02 11:23:44.625  32216-32229/ktl.myapplication D/dalvikvm﹕ init mutex
04-02 11:23:44.655  32216-32222/ktl.myapplication D/jdwp﹕ received file descriptor 47 from ADB
04-02 11:23:44.669  32216-32216/ktl.myapplication V/SettingsProviderInterface﹕ invalidate [system]: current 244 != cached 0
04-02 11:23:44.670  32216-32216/ktl.myapplication D/ActivityThread﹕ hoder:android.app.IActivityManager$ContentProviderHolder@43160db0,provider,holder.Provider:android.content.ContentProviderProxy@43161528
04-02 11:23:44.673  32216-32216/ktl.myapplication D/asset﹕ AssetManager-->addDefaultAssets CIP path not exsit!
04-02 11:23:44.676  32216-32216/ktl.myapplication D/Proxy﹕ setHttpRequestCheckHandler
04-02 11:23:44.678  32216-32216/ktl.myapplication D/dalvikvm﹕ open_cached_dex_file : /data/app/ktl.myapplication-2.apk /data/dalvik-cache/data@app@ktl.myapplication-2.apk@classes.dex
04-02 11:23:44.680  32216-32216/ktl.myapplication D/ActivityThread﹕ BIND_APPLICATION handled : 0 / AppBindData{appInfo=ApplicationInfo{4315e3e8 ktl.myapplication}}
04-02 11:23:44.680  32216-32216/ktl.myapplication V/ActivityThread﹕ Handling launch of ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}}
04-02 11:23:44.747  32216-32216/ktl.myapplication V/ActivityThread﹕ ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}}: app=android.app.Application@43165428, appName=ktl.myapplication, pkg=ktl.myapplication, comp={ktl.myapplication/ktl.myapplication.MainActivity}, dir=/data/app/ktl.myapplication-2.apk
04-02 11:23:44.749  32216-32216/ktl.myapplication D/dalvikvm﹕ create interp thread : stack size=128KB
04-02 11:23:44.749  32216-32216/ktl.myapplication D/dalvikvm﹕ create new thread
04-02 11:23:44.749  32216-32216/ktl.myapplication D/dalvikvm﹕ new thread created
04-02 11:23:44.749  32216-32216/ktl.myapplication D/dalvikvm﹕ update thread list
04-02 11:23:44.750  32216-32230/ktl.myapplication D/dalvikvm﹕ threadid=11: interp stack at 0x5f726000
04-02 11:23:44.750  32216-32230/ktl.myapplication D/dalvikvm﹕ init ref table
04-02 11:23:44.750  32216-32230/ktl.myapplication D/dalvikvm﹕ init mutex
04-02 11:23:44.750  32216-32230/ktl.myapplication D/dalvikvm﹕ threadid=11: created from interp
04-02 11:23:44.750  32216-32216/ktl.myapplication D/dalvikvm﹕ start new thread
04-02 11:23:44.750  32216-32230/ktl.myapplication D/dalvikvm﹕ threadid=11: notify debugger
04-02 11:23:44.750  32216-32230/ktl.myapplication D/dalvikvm﹕ threadid=11 (LaunchIconThemeResource): calling run()
04-02 11:23:44.757  32216-32216/ktl.myapplication D/asset﹕ AssetManager-->addDefaultAssets CIP path not exsit!
04-02 11:23:44.800  32216-32216/ktl.myapplication D/jiayh2﹕ LaunchIconThemeResourcegetDrawable packageName:ktl.myapplication asetfile:null
04-02 11:23:44.801  32216-32216/ktl.myapplication D/jiayh2﹕ LaunchIconThemeResourcegetDrawable packageName:ktl.myapplication asetfile:null
04-02 11:23:44.803  32216-32216/ktl.myapplication D/jiayh2﹕ LaunchIconThemeResourcegetDrawable packageName:ktl.myapplication asetfile:null
04-02 11:23:44.806  32216-32216/ktl.myapplication D/jiayh2﹕ LaunchIconThemeResourcegetDrawable packageName:ktl.myapplication asetfile:null
04-02 11:23:44.807  32216-32216/ktl.myapplication D/jiayh2﹕ LaunchIconThemeResourcegetDrawable packageName:ktl.myapplication asetfile:null
04-02 11:23:44.809  32216-32216/ktl.myapplication V/ActivityThread﹕ Performing resume of ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}} finished=false
04-02 11:23:44.809  32216-32216/ktl.myapplication D/ActivityThread﹕ ACT-AM_ON_RESUME_CALLED ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}}
04-02 11:23:44.809  32216-32216/ktl.myapplication V/ActivityThread﹕ Resume ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}} started activity: false, hideForNow: false, finished: false
04-02 11:23:44.854  32216-32216/ktl.myapplication V/PhoneWindow﹕ DecorView setVisiblity: visibility = 4 ,Parent =null, this =com.android.internal.policy.impl.PhoneWindow$DecorView{4316c030 I.E..... R.....ID 0,0-0,0}
04-02 11:23:44.968  32216-32216/ktl.myapplication V/ActivityThread﹕ Resuming ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}} with isForward=true
04-02 11:23:44.968  32216-32216/ktl.myapplication V/PhoneWindow﹕ DecorView setVisiblity: visibility = 0 ,Parent =ViewRoot{43179d90 ktl.myapplication/ktl.myapplication.MainActivity,ident = 0}, this =com.android.internal.policy.impl.PhoneWindow$DecorView{4316c030 V.E..... R.....ID 0,0-0,0}
04-02 11:23:44.968  32216-32216/ktl.myapplication V/ActivityThread﹕ Scheduling idle handler for ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}}
04-02 11:23:44.969  32216-32216/ktl.myapplication D/ActivityThread﹕ ACT-LAUNCH_ACTIVITY handled : 0 / ActivityRecord{4315fbe8 token=android.os.BinderProxy@4315f2d0 {ktl.myapplication/ktl.myapplication.MainActivity}}
04-02 11:23:44.971  32216-32216/ktl.myapplication D/jiayh2﹕ FontThemeManager createThemeFont typefacetype=2, curfontpath=/system/fonts/DroidSansFallback.ttf
04-02 11:23:44.971  32216-32216/ktl.myapplication D/jiayh2﹕ FontThemeManager createThemeFont typefacetype=2, curfontpath=/system/fonts/DroidSansFallback.ttf
04-02 11:23:44.971  32216-32216/ktl.myapplication D/jiayh2﹕ FontThemeManager createThemeFont typefacetype=2, curfontpath=/system/fonts/DroidSansFallback.ttf
04-02 11:23:45.040  32216-32216/ktl.myapplication D/IMGSRV﹕ mtk_gralloc_debug_check:43: g_gr_dbg=0 v=-1
04-02 11:23:45.040  32216-32216/ktl.myapplication D/IMGSRV﹕ mtk_gralloc_debug_check:43: g_gr_dbg=0 v=-1
04-02 11:23:45.059  32216-32216/ktl.myapplication D/GraphicBuffer﹕ create handle(0x604a6910) (w:1088, h:1920, f:1)
04-02 11:23:45.063  32216-32216/ktl.myapplication D/OpenGLRenderer﹕ Enabling debug mode 0
04-02 11:23:45.064  32216-32216/ktl.myapplication D/GraphicBuffer﹕ create handle(0x60cd26b0) (w:1792, h:1984, f:1)
04-02 11:23:45.071  32216-32216/ktl.myapplication D/OpenGLRenderer﹕ setViewport 1080x1920 <0x604a6a38>
04-02 11:23:45.073  32216-32216/ktl.myapplication V/InputMethodManager﹕ onWindowFocus: null softInputMode=288 first=true flags=#1810100
04-02 11:23:45.073  32216-32216/ktl.myapplication V/InputMethodManager﹕ START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{4316c030 V.E..... R.....ID 0,0-1080,1920} ic=null tba=android.view.inputmethod.EditorInfo@4318baf8 controlFlags=#104
04-02 11:23:46.466  32216-32216/ktl.myapplication I/View﹕ Touch down dispatch to android.widget.Button{43171f10 VFED..C. ........ 191,48-425,192 #7f08003f app:id/btn1}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=117.71414, y[0]=76.89589, Xw[0]=16.0, Yw[0]=16.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=56834756, downTime=56834756, deviceId=3, source=0x1002 }
04-02 11:23:46.487  32216-32216/ktl.myapplication D/GraphicBuffer﹕ create handle(0x61bf4b60) (w:1088, h:1920, f:1)
04-02 11:23:46.570  32216-32216/ktl.myapplication I/View﹕ Touch up dispatch to android.widget.Button{43171f10 VFED..C. ...P.... 191,48-425,192 #7f08003f app:id/btn1}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=112.71878, y[0]=74.89693, Xw[0]=32.0, Yw[0]=32.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=56834860, downTime=56834756, deviceId=3, source=0x1002 }
04-02 11:23:46.589  32216-32216/ktl.myapplication D/GraphicBuffer﹕ create handle(0x5f93dc58) (w:1088, h:1920, f:1)
04-02 11:23:48.835  32216-32216/ktl.myapplication I/View﹕ Touch down dispatch to android.widget.Button{43171f10 VFED..C. ........ 191,48-425,192 #7f08003f app:id/btn1}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=131.7012, y[0]=108.87923, Xw[0]=16.0, Yw[0]=16.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=56837124, downTime=56837124, deviceId=3, source=0x1002 }
04-02 11:23:48.869  32216-32216/ktl.myapplication D/GraphicBuffer﹕ create handle(0x61a99778) (w:1088, h:1920, f:1)
04-02 11:23:49.127  32216-32216/ktl.myapplication I/View﹕ Touch up dispatch to android.widget.Button{43171f10 VFED..C. ...P.... 191,48-425,192 #7f08003f app:id/btn1}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=131.7012, y[0]=108.87923, Xw[0]=32.0, Yw[0]=32.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=56837417, downTime=56837124, deviceId=3, source=0x1002 }
04-02 11:23:49.128  32216-32216/ktl.myapplication V/SettingsProviderInterface﹕ from settings cache , name = sound_effects_enabled , value = 0

我之前使用的代码是

public class MainActivity extends Activity {

    public String login;
    public String pass;
    private ProgressDialog dialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        login = "PAR";


    }

    public void svet1(View view) {
        //тут указываем куда будем конектится, для примера я привел удаленных хост если у вас не получилось освоить wamp (:

        pass = "SVET1";
        post();
    }
    public void post() {
        HttpClient httpClient = new DefaultHttpClient();
        // replace with your url
        HttpPost httpPost = new HttpPost("www.shkz3.info/switch.php");


        //Post Data
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("PAR", pass));



        //Encoding POST data
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        } catch (UnsupportedEncodingException e) {
            // log exception
            e.printStackTrace();
        }

        //making POST request.
        try {
            HttpResponse response = httpClient.execute(httpPost);
            // write response to log
            Log.d("Http Post Response:", response.toString());
        } catch (ClientProtocolException e) {
            // Log exception
            e.printStackTrace();
        } catch (IOException e) {
            // Log exception
            e.printStackTrace();
        }
    }


}

出现错误android.os.NetworkOnMainThreadException所以我尝试使用Asynctask

1 个答案:

答案 0 :(得分:0)

您没有执行,执行默认客户端并查找响应,您执行了postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));,之后您需要执行它。

Sending HTTP POST Request In Java

阅读Log.d("Http Post Response:", response.toString());,看看它返回了什么。我认为您的网址不适用于POST方法。