繁体   English   中英

android中http发布请求中的错误

[英]error in http post request in android

这是我的代码。 我在此方面遇到错误,请帮助我完成它。 我试图将带有一些数据的http请求发布到我的android应用中。

        package com.example.firstapp;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.firstapp.ShakeDetector.OnShakeListener;

public class MainActivity extends Activity {

    private CrystalBall mCrystalBall = new CrystalBall();
    private ApiCall mApiCall = new ApiCall();
    private TextView mAnswerLabel;
    private Button mGetAnswerButton;
    private ImageView mCrystalBallImage;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private ShakeDetector mShakeDetector;

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

        //Assign the Views from the layout file
        mAnswerLabel = (TextView) findViewById(R.id.textView1);
        mGetAnswerButton = (Button) findViewById(R.id.button1);
        mCrystalBallImage = (ImageView) findViewById(R.id.imageView1);

        mGetAnswerButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                handleNewAnswer();
                mApiCall.postData();
            }
        });

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mShakeDetector = new ShakeDetector(new OnShakeListener() {

            @Override
            public void onShake() {
                handleNewAnswer();
            }
        });
        //Toast.makeText(this, "Yes this is toast", Toast.LENGTH_LONG).show();
        //Log.d("Main Activity", "from oncreate() function");
    }

    @Override
    public void onResume() {
        super.onResume();
        mSensorManager.registerListener(mShakeDetector, mAccelerometer, 
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    public void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mShakeDetector);
    }

    private void animateCrystalBAll() {
        mCrystalBallImage.setImageResource(R.drawable.ball_animation);
        AnimationDrawable ballAnimtion = (AnimationDrawable) mCrystalBallImage.getDrawable();
        if(ballAnimtion.isRunning()) {
            ballAnimtion.stop();
        }
        ballAnimtion.start();
    }

    private void animateAnswer() {
        AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
        fadeInAnimation.setDuration(1500);
        fadeInAnimation.setFillAfter(true);
        mAnswerLabel.setAnimation(fadeInAnimation);
    }

    private void playSound() {
        MediaPlayer player = MediaPlayer.create(this, R.raw.crystal_ball);
        player.start();
        player.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
    }



}

这是ApiCall.java。 在此文件中,我正在使用http发布请求

package com.example.firstapp;

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

public class ApiCall extends AsyncTask {
    public void postData() {
        HttpClient httpclient = new DefaultHttpClient();    
          HttpPost httppost = new HttpPost("http://dailydeal.in/android/Api.php");      
                try {        

                     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
                     nameValuePairs.add(new BasicNameValuePair("gmail","mail@gmail.com"));

                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
                    HttpResponse response = httpclient.execute(httppost);             
                 } 
                catch (ClientProtocolException e) 
                {       
                     e.printStackTrace(); 
                 } 
                catch (IOException e) 
                {         
                     e.printStackTrace();
                  }
    }

    @Override
    protected Object doInBackground(Object... arg0) {
        // TODO Auto-generated method stub
        return null;
    } 
}
  • 请确保您已请求清单上的INTERNET权限

  • postData()函数必须在单独的线程上调用,因为您不能在主线程上运行请求网络。 您可以使用Asynctask或服务

    私有类PostDataAsynTask扩展了AsyncTask {

     @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } @Override protected ApiModel doInBackground(String... params) { // Call your post data funciton here return null; } @Override protected void onPostExecute(ApiModel result) { // TODO Auto-generated method stub super.onPostExecute(result); // Do your stuff after post data here } 

    }

然后在你身上

new PostDataAsynTask().excute("");

尝试这个

  HttpClient httpclient = new DefaultHttpClient();    
  HttpPost httppost = new HttpPost(YOUR URL);      
        try {        

             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
             nameValuePairs.add(new BasicNameValuePair("gmail","mail@gmail.com"));

             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
            HttpResponse response = httpclient.execute(httppost);             
         } 
        catch (ClientProtocolException e) 
        {       
             e.printStackTrace(); 
         } 
        catch (IOException e) 
        {         
             e.printStackTrace();
          }

确保您的数据库包含字段“ gmail”

PHP

   <?php

    mysql_connect("localhost","username","password");

    mysql_select_db("db_name"); 


    $a1= (isset($_POST['gmail'])) ? $_POST['gmail'] : '';

    $ins="insert into Table_name(gmail)values('$a1')";

    mysql_query($ins);
     mysql_close();
   ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM