改造2:即使有,也没有请求机构

时间:2017-12-23 08:56:30

标签: php android json retrofit retrofit2

你有没遇到过这个问题?我使用retrofit2发出了一个Post请求,但是请求正文不会提供给服务器。上次我检查了Feed它是空的,这就是为什么它无法通过IF语句。这是我的代码:

 Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit newAccountRetro = new Retrofit.Builder()
            .baseUrl("http://192.168.1.8/waterdistrict/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RetrofitAPI retroAPI = newAccountRetro.create(RetrofitAPI.class);

我的要求人:

    NewFormRequest nfr = new NewFormRequest();
    nfr.setFname(fname);
    nfr.setMname(mname);
    nfr.setLname(lname);
    nfr.setUsern(usern);
    nfr.setPs(ps);
    nfr.setContact(contact);
    nfr.setAdd(add);
    nfr.setEmail(email);

    rs = new Presenter(context);
    //TODO:Fix null response of Retrofit

这是我通过请求正文的方式

   Call<NewFormResponse> nfResponse = retroAPI.newAccount((NewFormRequest) nfr);
    nfResponse.enqueue(new Callback<NewFormResponse>() {
        @Override
        public void onResponse(Call<NewFormResponse> call, Response<NewFormResponse> response) {
            Log.d(getClass().toString(), response.code()+"-"+new Gson().toJson(response.body())
                    +"-"+call.request().toString()+" - "+call.request().headers().toString());
            if(response.code() == 200){
                rs.nfResponse(response.body().getCode(), response.body().getMessage());
                rs.switchProgress();
            }
        };

        @Override
        public void onFailure(Call<NewFormResponse> call, Throwable t) {
            rs.switchProgress();
            Log.d(getClass().toString(), t.toString());

        }
    });

ENDPOINT:

 @POST("addClients.php")
Call<NewFormResponse> newAccount (@Body NewFormRequest newFormRequest);

NewFormResponse:

public class NewFormResponse {
@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;

public Integer getCode() {
    return code;
}

public void setCode(Integer code) {
    this.code = code;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}
}

newFormRequest类

public class NewFormRequest {
private String fname;
private String mname;
private String lname;
private String usern;
private String ps;
private String contact;
private String add;
private String email;

public String getFname() {
    return fname;
}

public void setFname(String fname) {
    this.fname = fname;
}

public String getMname() {
    return mname;
}

public void setMname(String mname) {
    this.mname = mname;
}

public String getLname() {
    return lname;
}

public void setLname(String lname) {
    this.lname = lname;
}

public String getUsern() {
    return usern;
}

public void setUsern(String usern) {
    this.usern = usern;
}

public String getPs() {
    return ps;
}

public void setPs(String ps) {
    this.ps = ps;
}

public String getContact() {
    return contact;
}

public void setContact(String contact) {
    this.contact = contact;
}

public String getAdd() {
    return add;
}

public void setAdd(String add) {
    this.add = add;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
} 

PHP代码

<?php
include "connection.php";

if(mysqli_connect_errno()){
    $response["code"] = 0;
    $response["message"] = "failed to connect with the database";
    echo json_encode($response);
} else{
        if(isset($_POST['fname'], $_POST['mname'], $_POST['lname'], $_POST['usern'], $_POST['ps'], $_POST['contact'], $_POST['add'], $_POST['email'])){
            $fname = $_POST['fname'];
            $mname = $_POST['mname'];
            $lname = $_POST['lname'];
            $contactnum = $_POST['contact'];
            $address = $_POST['add'];
            $email = $_POST['email'];
            $usern = $_POST['usern'];
            $password = $_POST['ps'];
            $approval = 0;

            try{
                $conni = new PDO("mysql:host=localhost;dbname=wddatabase","root","");
                $conni->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $sql_insert = "INSERT INTO clients (fname, mname, lname,  uname, password, contact_num, address, email, approved) 
                    VALUES ('$fname', '$mname', '$lname', '$usern', '$password', '$contactnum', '$address', '$email', '$approval')";
                $conni->exec($sql_insert);
                $response['code']= 1;
                $response['message']='New Record Created';
                echo json_encode($response);
            }catch(PDOException $e){
                $response['code']= 0;
                $response['message']=$e;
                echo json_encode($response);
            }
        } else{
            $response['code']= 0;
                $response['message']="Error";
                echo json_encode($response);
        }
}

?>

// RESULT

200-{"code":0,"message":"Error"}-Request{method=POST, url=http://192.168.1.8/waterdistrict/addClients.php, tag=null} - 

2 个答案:

答案 0 :(得分:0)

在php中你应该在echo json结果之前将头设置为json:

 header('Content-Type: application/json');
 echo $json;

答案 1 :(得分:0)

Javadocs进行身体注释的改造。

  

使用Retrofit实例Converter将对象序列化   并且结果将直接设置为请求正文。

我会说转换器在将NewFormRequest类转换为HTTP

时遇到问题

如果您将NewFormRequest类放在OkHttp3 RequestBody中,那么将允许转换。

如果您正在使用(或愿意使用)JSON作为RequestBody的MediaType,这应该可行。

端点:

    @POST("addClients.php")
    Call<NewFormResponse> newAccount (@Body RequestBody newFormRequest);

并调用代码:

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("myJsonTag", nfr);
    String jsonString = new Gson().toJson(jsonObject);

    RequestBody nfrBody = RequestBody.create(MediaType.parse(CONTENT_JSON), jsonString);

    Call<NewFormResponse> nfResponse = retroAPI.newAccount(nfrBody);
    nfResponse.enqueue(new Callback<NewFormResponse>() {...