duanqin4238
duanqin4238
2019-07-27 13:41

如何正确地将数据从Android App发布到PHP?

已采纳

I'm developing an app that has to post user data to database (login,password,id of device, latitude and longitude). I'm trying to POST it through PHP, but i get eror "End of input at line 1 column 1 path $".

I'm not sure what should I do.

I was trying to do something with gson, but it didn't work also. If anyone has any idea, please let me know... :)

Here is my MainActivity Code:

public void createPost(String loginStr, String passwordStr, String id_urzadzenia, double latitude, double longitude) throws IOException {
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://unpreached-courtesy.000webhostapp.com")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
    API ApiPlaceHolder = retrofit.create(API.class);

    Call<Post> call = ApiPlaceHolder
            .createPost(
                    loginStr,
                    passwordStr,
                    id_urzadzenia,
                    latitude,
                    longitude);

    call.enqueue(new Callback<Post>() {
        @Override
        public void onResponse(Call<Post> call, Response<Post> response) {
            if (!response.isSuccessful()) {
                Toast.makeText(MainActivity.this, "Code " + response.code(), Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onFailure(Call<Post> call, Throwable t) {
            Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
            Toast.makeText(MainActivity.this, call.request().toString(), Toast.LENGTH_SHORT).show();
        }
    });

}

API Interface code:

public interface API {
    @FormUrlEncoded
    @POST("/dane.php")
        Call<Post> createPost (
                @Field("loginStr")String loginStr,
                @Field("passwordStr") String passwordStr,
                @Field("id_urzadzenia") String id_urzadzenia,
                @Field("latitude") double latitude,
                @Field("longitude") double longitude
                );
}

Post.java class code:

public class Post {
    private String loginStr;

    private String passwordStr;

    private String id_urzadzenia;

    private double latitude;
    private double longitude;

    public String getLoginStr() {
        return loginStr;
    }

    public void setLoginStr(String loginStr) {
        this.loginStr = loginStr;
    }

    public String getPasswordStr() {
        return passwordStr;
    }

    public void setPasswordStr(String passwordStr) {
        this.passwordStr = passwordStr;
    }

    public String getId_urzadzenia() {
        return id_urzadzenia;
    }

    public void setId_urzadzenia(String id_urzadzenia) {
        this.id_urzadzenia = id_urzadzenia;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
}

And there is my PHP:

    <?php header('Content-Type: application/json');



$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);


$login = $_POST["loginStr"];
$id_urz = $_POST["id_urzadzenia"];
$dl_geo = $_POST["longitude"];
$sz_geo = $_POST["latitude"];
echo "Login użytkownika: " .$login . "
";
echo "ID urządzenia: " . $id_urz . "
";
echo "Szerokość geograficzna: " . $sz_geo . "
";
echo "Długość geograficzna: " . $dl_geo . "
";
date_default_timezone_get(Europe);
$godz =  date("H:i:s");
$sql = "INSERT INTO TABLE bartek (id_urzadzenia,szerokosc,dlugosc,data) VALUES ('".json_encode($id_urz)."','".json_encode($sz_geo)."','".json_encode($dl_geo)."','".$godz."'";

mysqli_query($con, $sql);
mysqli_close($con);
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsnm64969 dsnm64969 2年前

    try this

    in Gradle

            implementation 'com.google.code.gson:gson:2.8.5'
            implementation 'com.squareup.retrofit2:retrofit:2.5.0'
            implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
            implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'    
    

    in Interface eg: make RetrofitAPI.java

    
            public static PostService postService = null;
    
            public static PostService getService() {
              if (postService == null) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor).build();
    
                Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
                postService = retrofit.create(PostService.class);
    
               }
              return postService;
            }
            public interface API {
                @FormUrlEncoded
                @POST
                Call<Post> createPost(@Url String url,
                                           @Field("id_urzadzenia") String id_urzadzenia,
                        @Field("loginStr") String loginStr,
                        @Field("passwordStr") String passwordStr,
                        @Field("longitude") String longitude,
                        @Field("latitude") String latitude
                                           );
            }
    
    

    in MainActivity

    public void createPost(String loginStr, String passwordStr, String id_urzadzenia, double latitude, double longitude) throws IOException {
         final Call<Post> call_api = RetrofitAPI.getService().createPost(url, id_urzadzenia, loginStr, passwordStr, longitude, latitude );
                call_api.enqueue(new Callback<Post>() {
                    @Override
                    public void onResponse(Call<Post> call, Response<Post> response) {
                            if(response.body() != null){
    
                                // Toast.makeText(ACTIVITY.this, "Success!!!", Toast.LENGTH_SHORT).show();
                            }
                        }
    
                        @Override
                        public void onFailure(Call<Post> call, Throwable t) {
                            // Toast.makeText(ACTIVITY.this, "Error Occured", Toast.LENGTH_SHORT).show();
    
                        }
    
                    });
                }
    
    }
    

    Change your php file like this. now it should insert into your database

    //your database configuration
    
    $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
    
    
    $login = $_POST["loginStr"];
    $id_urz = $_POST["id_urzadzenia"];
    $dl_geo = $_POST["longitude"];
    $sz_geo = $_POST["latitude"];
    // echo "Login użytkownika: " .$login . "
    ";
    // echo "ID urządzenia: " . $id_urz . "
    ";
    // echo "Szerokość geograficzna: " . $sz_geo . "
    ";
    // echo "Długość geograficzna: " . $dl_geo . "
    ";
    date_default_timezone_get(Europe);
    $godz =  date("H:i:s");
    $sql = "INSERT INTO bartek (id_urzadzenia,szerokosc,dlugosc,data) VALUES ('$id_urz','$sz_geo','$dl_geo','$godz')";
    
    mysqli_query($con, $sql);
    mysqli_close($con);
    ?>
    
    点赞 评论 复制链接分享