Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 改装2不';不要发送POST数据_Java_Android_Post_Retrofit_Retrofit2 - Fatal编程技术网

Java 改装2不';不要发送POST数据

Java 改装2不';不要发送POST数据,java,android,post,retrofit,retrofit2,Java,Android,Post,Retrofit,Retrofit2,对不起,如果我的英语不好!我使用改装2来接收依赖于POST数据的数据。我从服务器接收数据,但在发送数据时遇到问题。我曾尝试使用不同的注释(@Field、@Body和Object、@Body和HashMap数据),但每种注释都不起作用。 以下是我的Java代码: build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { ap

对不起,如果我的英语不好!我使用改装2来接收依赖于POST数据的数据。我从服务器接收数据,但在发送数据时遇到问题。我曾尝试使用不同的注释(@Field、@Body和Object、@Body和HashMap数据),但每种注释都不起作用。 以下是我的Java代码:

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.test.retrofitpostdatagetjson"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.google.code.gson:gson:2.8.4'

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'

    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
APIClient.java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIClient {
    private static final String BASE_URL = "https://myurl.ru/";
    private static Retrofit retrofit;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
public class ApiUtils {

    private ApiUtils() {}

    public static APIInterface getAPIService() {

        return APIClient.getClient().create(APIInterface.class);
    }
}
import com.test.retrofitpostdatagetjson.model.DataResponse;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface APIInterface {
    @POST("test_json_with_post")
    Call<DataResponse> createData(@Body DataResponse data);

}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;

public class DataResponse implements Serializable {

    @SerializedName("numb")
    @Expose
    private int numb;
    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("emp")
    @Expose
    public String value;
    @SerializedName("status")
    @Expose
    public String status;

    public DataResponse(int numb, String name) {
        this.numb = numb;
        this.name = name;
    }

    public int getNumb() {
        return numb;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public String getStatus() {
        return status;
    }

    public void setNumb(int numb) {
        this.numb = numb;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "DataResponse{" +
                "numb=" + numb +
                ", name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", status='" + status + '\'' +
                '}';
    }
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.test.retrofitpostdatagetjson.api.APIInterface;
import com.test.retrofitpostdatagetjson.model.DataResponse;
import static com.test.retrofitpostdatagetjson.api.ApiUtils.getAPIService;

public class MainActivity extends AppCompatActivity {

    APIInterface apiInterface;
    int numb = 0;
    String name = "test row";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        apiInterface = getAPIService();

        if (CommonMethod.isNetworkAvailable(MainActivity.this))
            sendPost(numb, name);
        else
            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);

    }

    private void sendPost(int numb, String name) {

        final DataResponse data = new DataResponse(numb, name);
        Log.w("retroTest", "sent    -->  " + data.toString());
        Call<DataResponse> call1 = apiInterface.createData(data);
        call1.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                DataResponse dataResponse = response.body();
                if (dataResponse != null) {
                    Log.w("retroTest", "received    -->  " + dataResponse.toString());
                }
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                call.cancel();
            }
        });
    }

}
ApiUtils.java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIClient {
    private static final String BASE_URL = "https://myurl.ru/";
    private static Retrofit retrofit;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
public class ApiUtils {

    private ApiUtils() {}

    public static APIInterface getAPIService() {

        return APIClient.getClient().create(APIInterface.class);
    }
}
import com.test.retrofitpostdatagetjson.model.DataResponse;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface APIInterface {
    @POST("test_json_with_post")
    Call<DataResponse> createData(@Body DataResponse data);

}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;

public class DataResponse implements Serializable {

    @SerializedName("numb")
    @Expose
    private int numb;
    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("emp")
    @Expose
    public String value;
    @SerializedName("status")
    @Expose
    public String status;

    public DataResponse(int numb, String name) {
        this.numb = numb;
        this.name = name;
    }

    public int getNumb() {
        return numb;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public String getStatus() {
        return status;
    }

    public void setNumb(int numb) {
        this.numb = numb;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "DataResponse{" +
                "numb=" + numb +
                ", name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", status='" + status + '\'' +
                '}';
    }
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.test.retrofitpostdatagetjson.api.APIInterface;
import com.test.retrofitpostdatagetjson.model.DataResponse;
import static com.test.retrofitpostdatagetjson.api.ApiUtils.getAPIService;

public class MainActivity extends AppCompatActivity {

    APIInterface apiInterface;
    int numb = 0;
    String name = "test row";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        apiInterface = getAPIService();

        if (CommonMethod.isNetworkAvailable(MainActivity.this))
            sendPost(numb, name);
        else
            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);

    }

    private void sendPost(int numb, String name) {

        final DataResponse data = new DataResponse(numb, name);
        Log.w("retroTest", "sent    -->  " + data.toString());
        Call<DataResponse> call1 = apiInterface.createData(data);
        call1.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                DataResponse dataResponse = response.body();
                if (dataResponse != null) {
                    Log.w("retroTest", "received    -->  " + dataResponse.toString());
                }
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                call.cancel();
            }
        });
    }

}
apinterface.java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIClient {
    private static final String BASE_URL = "https://myurl.ru/";
    private static Retrofit retrofit;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
public class ApiUtils {

    private ApiUtils() {}

    public static APIInterface getAPIService() {

        return APIClient.getClient().create(APIInterface.class);
    }
}
import com.test.retrofitpostdatagetjson.model.DataResponse;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface APIInterface {
    @POST("test_json_with_post")
    Call<DataResponse> createData(@Body DataResponse data);

}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;

public class DataResponse implements Serializable {

    @SerializedName("numb")
    @Expose
    private int numb;
    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("emp")
    @Expose
    public String value;
    @SerializedName("status")
    @Expose
    public String status;

    public DataResponse(int numb, String name) {
        this.numb = numb;
        this.name = name;
    }

    public int getNumb() {
        return numb;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public String getStatus() {
        return status;
    }

    public void setNumb(int numb) {
        this.numb = numb;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "DataResponse{" +
                "numb=" + numb +
                ", name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", status='" + status + '\'' +
                '}';
    }
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.test.retrofitpostdatagetjson.api.APIInterface;
import com.test.retrofitpostdatagetjson.model.DataResponse;
import static com.test.retrofitpostdatagetjson.api.ApiUtils.getAPIService;

public class MainActivity extends AppCompatActivity {

    APIInterface apiInterface;
    int numb = 0;
    String name = "test row";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        apiInterface = getAPIService();

        if (CommonMethod.isNetworkAvailable(MainActivity.this))
            sendPost(numb, name);
        else
            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);

    }

    private void sendPost(int numb, String name) {

        final DataResponse data = new DataResponse(numb, name);
        Log.w("retroTest", "sent    -->  " + data.toString());
        Call<DataResponse> call1 = apiInterface.createData(data);
        call1.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                DataResponse dataResponse = response.body();
                if (dataResponse != null) {
                    Log.w("retroTest", "received    -->  " + dataResponse.toString());
                }
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                call.cancel();
            }
        });
    }

}
MainActivity.java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIClient {
    private static final String BASE_URL = "https://myurl.ru/";
    private static Retrofit retrofit;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
public class ApiUtils {

    private ApiUtils() {}

    public static APIInterface getAPIService() {

        return APIClient.getClient().create(APIInterface.class);
    }
}
import com.test.retrofitpostdatagetjson.model.DataResponse;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface APIInterface {
    @POST("test_json_with_post")
    Call<DataResponse> createData(@Body DataResponse data);

}
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;

public class DataResponse implements Serializable {

    @SerializedName("numb")
    @Expose
    private int numb;
    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("emp")
    @Expose
    public String value;
    @SerializedName("status")
    @Expose
    public String status;

    public DataResponse(int numb, String name) {
        this.numb = numb;
        this.name = name;
    }

    public int getNumb() {
        return numb;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public String getStatus() {
        return status;
    }

    public void setNumb(int numb) {
        this.numb = numb;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "DataResponse{" +
                "numb=" + numb +
                ", name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", status='" + status + '\'' +
                '}';
    }
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.test.retrofitpostdatagetjson.api.APIInterface;
import com.test.retrofitpostdatagetjson.model.DataResponse;
import static com.test.retrofitpostdatagetjson.api.ApiUtils.getAPIService;

public class MainActivity extends AppCompatActivity {

    APIInterface apiInterface;
    int numb = 0;
    String name = "test row";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        apiInterface = getAPIService();

        if (CommonMethod.isNetworkAvailable(MainActivity.this))
            sendPost(numb, name);
        else
            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);

    }

    private void sendPost(int numb, String name) {

        final DataResponse data = new DataResponse(numb, name);
        Log.w("retroTest", "sent    -->  " + data.toString());
        Call<DataResponse> call1 = apiInterface.createData(data);
        call1.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                DataResponse dataResponse = response.body();
                if (dataResponse != null) {
                    Log.w("retroTest", "received    -->  " + dataResponse.toString());
                }
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                call.cancel();
            }
        });
    }

}
服务器上的我的PHP文件:

W/retroTest: sent  -->  DataResponse{numb=0, name='test row', value='null', status='null'}
W/retroTest: received  -->  DataResponse{numb=0, name='null', value='null', status='2'}
<?php
header("Content-type: application/json; charset=utf-8");

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

$numb = $input['numb'];
$name = $input['name'];

if (isset($_POST['numb']) && !empty($_POST['numb'])) {   
  $numb = $_POST['numb']; }
if (isset($_POST['name']) && !empty($_POST['name'])) {   
  $name = $_POST['name']; }

if (!$numb) {
$json = json_encode( array(
"emp" => $name,
"status" => "2"));
} else {
$json = json_encode( array(
"emp" => "nothing",
"status" => "2"));
}

$myfile = fopen("testfile.txt", "w");
fwrite($myfile, $inputJSON);
fwrite($myfile, "\n");
fwrite($myfile, $numb);
fwrite($myfile, "\n");
fwrite($myfile, $name);
fclose($myfile);


echo $json;
?>

文件testfile.txt也是空的,但当我试图通过邮递员发送邮件时,一切都正常!

您是否尝试将body作为JsonObject发送? 总是对我有用。如果不是,那么我会假设后端端口有问题

大概是这样的:

public interface APIInterface {
    @POST("test_json_with_post")
    Call<DataResponse> createData(@Body JsonObject data);

}

你试过把尸体作为JsonObject发送吗? 总是对我有用。如果不是,那么我会假设后端端口有问题

大概是这样的:

public interface APIInterface {
    @POST("test_json_with_post")
    Call<DataResponse> createData(@Body JsonObject data);

}

我已经找到了我问题的原因。。太简单了。。这都是关于url末尾的斜杠。 我使用index.php,所以当我将帖子发送到我的url地址时,应该以斜杠结尾

相反,这是:

 @POST("test_json_with_post")
我应该这样写:

 @POST("test_json_with_post/")
在我的apinterface.java中。一切正常


希望,有一天它会帮助别人)我已经找到了问题的原因。。太简单了。。这都是关于url末尾的斜杠。 我使用index.php,所以当我将帖子发送到我的url地址时,应该以斜杠结尾

相反,这是:

 @POST("test_json_with_post")
我应该这样写:

 @POST("test_json_with_post/")
在我的apinterface.java中。一切正常


希望,有一天它会帮助别人)

postman中的url是否与“/test\u json\u with\u post”相同?此外,我没有看到为“sent-->”Log编写的代码可能与uneq95重复,是的,postman中的url是相同的,而且我在我的应用程序中从它接收数据,问题只是从应用程序发送数据。关于“发送-->”日志-抱歉,在将MainActivity的代码粘贴到我的问题后,我更改了这些行。现在修复了。Prim,这个问题的答案对我没有帮助,可能是我代码中出现问题的原因。postman中的url是否与“/test\u json\u with\u post”相同?此外,我没有看到为“sent-->”Log编写的代码可能与uneq95重复,是的,postman中的url是相同的,而且我在我的应用程序中从它接收数据,问题只是从应用程序发送数据。关于“发送-->”日志-抱歉,在将MainActivity的代码粘贴到我的问题后,我更改了这些行。现在修复了。Prim,这个问题的答案对我没有帮助,可能是我代码中出现问题的原因。我不能完全按照您编写的方式来做,因为Android Studio告诉我“不兼容的类型。必需:com.google.gson.JsonObject发现:java.lang.String”。我这样做:JSONObject obj=newjsonobject(newgson().toJson(data));但它仍然没有解决我的问题problem@MariaJSONObject和JSONObject是两个不同的对象。第一个是默认的java库实现,第二个是Gson库实现。您可能应该使用第二个。检查您的导入并删除JSONObject:)Yury Dombaev,我理解,JSONObject和JSONObject是两个不同的对象。正如您在我的评论中看到的,我尝试使用com.google.gson.JsonObject并收到一个错误(不兼容的类型),因为方法toJson(objectsrc)返回String。。“我不明白如何正确地修复它。)@Maria哦,对不起,看来我给你的方法不对。你能试试这个吗
JsonElement-JsonElement=gson.toJsonTree(javaObject);JsonObject JsonObject=(JsonObject)jsonElement我不能完全按照您编写的方式执行,因为Android Studio告诉我“不兼容的类型。必需:com.google.gson.JsonObject-find:java.lang.String”。我这样做:JSONObject obj=newjsonobject(newgson().toJson(data));但它仍然没有解决我的问题problem@MariaJSONObject和JSONObject是两个不同的对象。第一个是默认的java库实现,第二个是Gson库实现。您可能应该使用第二个。检查您的导入并删除JSONObject:)Yury Dombaev,我理解,JSONObject和JSONObject是两个不同的对象。正如您在我的评论中看到的,我尝试使用com.google.gson.JsonObject并收到一个错误(不兼容的类型),因为方法toJson(objectsrc)返回String。。“我不明白如何正确地修复它。)@Maria哦,对不起,看来我给你的方法不对。你能试试这个吗
JsonElement-JsonElement=gson.toJsonTree(javaObject);JsonObject JsonObject=(JsonObject)jsonElement