android中的http post请求中的错误

时间:2014-04-28 09:36:27

标签: android http post

这是我的代码。我在这收到错误,请帮我完成。  我想在我的Android应用程序中使用一些数据向我的服务器发布一个http请求。

        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 post request

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

2 个答案:

答案 0 :(得分:1)

  • 请确保您已在清单

    上请求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
    }
    

    }

然后是你的MainActivity

new PostDataAsynTask().excute("");

答案 1 :(得分:0)

试试这个

  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();
          }

确保您的数据库包含字段&#34; gmail&#34;

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();
   ?>