java - 如何在Android应用程序中发出HTTP请求

标签 java php android

我是 Android 的新开发人员,我对 Java 或 Android 没有太多经验。我正在寻找一种将 POST 数据发送到 PHP 脚本并显示结果的方法。这是我制作的android程序,用于在在线mysql服务器上发送数据,但是当我插入数据时,它会插入空值,这是我的android java代码

 package com.example.myapp.myapplication;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import android.view.Menu;
import android.widget.Toast;

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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements LocationListener{
    LocationManager lm;
    TextView lt, ln;
    String provider;
    Location l;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ln=(TextView)findViewById(R.id.lng);
        lt=(TextView)findViewById(R.id.lat);
        //get location service
        lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        Criteria c=new Criteria();
        //criteria object will select best service based on
        //Accuracy, power consumption, response, bearing and monetary cost
        //set false to use best service otherwise it will select the default Sim network
        //and give the location based on sim network
        //now it will first check satellite than Internet than Sim network location
        provider=lm.getBestProvider(c, false);
        //now you have best provider
        //get location
        l=lm.getLastKnownLocation(provider);
        if(l!=null)
        {
            //get latitude and longitude of the location
            double lng=l.getLongitude();
            double lat=l.getLatitude();
            //display on text view
            ln.setText(""+lng);
            lt.setText(""+lat);
        }
        else
        {
            ln.setText("No Provider");
            lt.setText("No Provider");
        }
    }
    //If you want location on changing place also than use below method
    //otherwise remove all below methods and don't implement location listener
    @Override
    public void onLocationChanged(Location arg0)
    {
        double lng=l.getLongitude();
        double lat=l.getLatitude();
        ln.setText(""+lng);
        lt.setText(""+lat);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void insert(View view){
        String lati = lt.getText().toString();
        String longi = ln.getText().toString();

        insertToDatabase(lati,longi);
    }
    private void insertToDatabase(final String lt, final String ln) {
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                String paramlt = params[0];
                String paramln = params[1];

                List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("latitude", paramlt));
                nameValuePairs.add(new BasicNameValuePair("Longitude", paramln));

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://calcare.pk/insert.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
                textViewResult.setText("Inserted");
            }
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        String[] str = new String[2];
        str[0] = lt;
        str[1] = ln ;
        sendPostReqAsyncTask.execute(str);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
    }

  }

这也是我的 PHP 脚本

<?php
$host='1.2.3.4';
$uname='android';
$pwd='asdfghj';
$db="asdf";

$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");

$Latitude = $_POST['lt'];
   $Longitude = $_POST['ln'];

$flag['code']=0;

if($r=mysql_query("insert into sample (latitude,Longitude) values ('$Latitude','$Longitude')",$con))
{
    $flag['code']=1;
    echo"hi";
}

print(json_encode($flag));
mysql_close($con);

?>

最佳答案

您从 android 传递“纬度”,并从 php 获取它作为 $_POST['lt']

它如何工作,两个 key 应该相同

关于java - 如何在Android应用程序中发出HTTP请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560828/

相关文章:

java - 为什么使用工厂方法模式而不是简单工厂

Java 如何使用 Graphics2D 制作抗锯齿线?

java - 如何托管小部件以及如何始终可靠地更新它们?

java - 相机方向改变

java - 智能 JScrollPane 自动滚动

java - Android : Gradle update from 2. 10 到 2.4 失败

php - 生成唯一的 6 位代码

php - if/elseif `isset` 多个提交输入不起作用

php - 如何在 PHP 中将公历日期(以秒为单位)转换为 unix 时间戳

android - Fusionlocationprovider 在 android 中没有 gps 时无法工作