简体   繁体   English

在Android中进行Json请求和响应

[英]Making a Json Request and Response in Android

I'm trying to make a Json Request and response in android, but i'm new and i need examples to how to make this.. 我正在尝试在android中进行Json请求和响应,但是我是新手,因此我需要示例来说明如何实现这一点。

Make the Connection: 建立连接:

public class ServiceGeneratorCpf {

//URL base do endpoint. Deve sempre terminar com /
public static final String API_BASE_URL = "http://www.soawebservices.com.br/";

public static <S> S createService(Class<S> serviceClass) {

    //Instancia do interceptador das requisições
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
            .readTimeout(15, TimeUnit.SECONDS);

    httpClient.addInterceptor(loggingInterceptor);


    //Instância do retrofit
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(new Gson()))
            .client(httpClient.build())
            .build();

    return retrofit.create(serviceClass);
}

Model: 模型:

public class RespostaServidorCpf {

private String result;
private Boolean valid;
private String Email;
private String Senha;
private String Documento;
private String Nome;
private String DataNascimento;
private String DataInscricao;
private String AnoObito;
private String MensagemObito;
private String CodigoSituacaoCadastral;
private String SituacaoRFB;
private Date DataConsultaRFB;
private String ProtocoloRFB;
private String DigitoVerificador;
private String Mensagem;
private Boolean Status;

public RespostaServidorCpf(){

}

public String getResult() {
    return result;
}

public boolean isValid() {
    return valid;
}

public void setValid(boolean valid) {
    this.valid = valid;
}

public void setResult(String result) {
    this.result = result;
}

public String getDocumento() {
    return Documento;
}

public void setDocumento(String Documento) {
    this.Documento = Documento;
}


public String getNome() {
    return Nome;
}

public void setNome(String nome) {
    Nome = nome;
}

public String getDataNascimento() {
    return DataNascimento;
}

public void setDataNascimento(String dataNascimento) {
    DataNascimento = dataNascimento;
}

public String getDataInscricao() {
    return DataInscricao;
}

public void setDataInscricao(String dataInscricao) {
    DataInscricao = dataInscricao;
}

public String getAnoObito() {
    return AnoObito;
}

public void setAnoObito(String anoObito) {
    AnoObito = anoObito;
}

public String getMensagemObito() {
    return MensagemObito;
}

public void setMensagemObito(String mensagemObito) {
    MensagemObito = mensagemObito;
}

public String getCodigoSituacaoCadastral() {
    return CodigoSituacaoCadastral;
}

public void setCodigoSituacaoCadastral(String codigoSituacaoCadastral) {
    CodigoSituacaoCadastral = codigoSituacaoCadastral;
}

public String getSituacaoRFB() {
    return SituacaoRFB;
}

public void setSituacaoRFB(String situacaoRFB) {
    SituacaoRFB = situacaoRFB;
}

public Date getDataConsultaRFB() {
    return DataConsultaRFB;
}

public void setDataConsultaRFB(Date dataConsultaRFB) {
    DataConsultaRFB = dataConsultaRFB;
}

public String getProtocoloRFB() {
    return ProtocoloRFB;
}

public void setProtocoloRFB(String protocoloRFB) {
    ProtocoloRFB = protocoloRFB;
}

public String getDigitoVerificador() {
    return DigitoVerificador;
}

public void setDigitoVerificador(String digitoVerificador) {
    DigitoVerificador = digitoVerificador;
}

public String getMensagem() {
    return Mensagem;
}

public void setMensagem(String mensagem) {
    Mensagem = mensagem;
}

public Boolean getStatus() {
    return Status;
}

public void setStatus(Boolean status) {
    Status = status;
}

public String getEmail() {
    return Email;
}

public void setEmail(String email) {
    Email = email;
}

public String getSenha() {
    return Senha;
}

public void setSenha(String senha) {
    Senha = senha;
}

Interface: 接口:

public interface RetrofitService {

@Headers({
        "Content-Type: application/json"
})

@FormUrlEncoded
@POST("restservices/producao/cdc/pessoafisicanfe.ashx")
Call<RespostaServidorCpf> mostrarConsultaCpf(@Field("Email") String Email,
                                             @Field("Senha") String Senha,
                                             @Field("Documento") String Documento,
                                             @Field("DataNascimento") String DataNascimento);

} }

Where I receive the Json Response: 我收到Json回应的地方:

public class ResultConsCpfActivity extends AppCompatActivity {

RespostaServidorCpf resposta = new RespostaServidorCpf();
private ProgressDialog progress;
private String Senha;
private String Email;
private TextView txtDocumento;
private TextView txtNome;
private TextView txtDataNascimento;
private TextView txtDataInscricao;
private TextView txtAnoObito;
private TextView txtMensagemObito;
private TextView txtCodigoSituacaoCadastral;
private TextView txtSituacaoRFB;
private TextView txtDataConsultaRFB;
private TextView txtProtocoloRFB;
private TextView txtDigitoVerificador;
private TextView txtMensagem;
private TextView txtStatus;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result_cons_cpf);

    Email = "pedrofarbo@gmail.com";
    Senha = "efTE8zjwC";

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String date = bundle.getString("date");
    String cpf = bundle.getString("cpf");

    txtDocumento = (TextView) findViewById(R.id.txtDocumento);
    txtNome = (TextView) findViewById(R.id.txtNome);
    txtDataNascimento = (TextView) findViewById(R.id.txtDataNascimento);
    txtDataInscricao = (TextView) findViewById(R.id.txtDataInscricao);
    txtAnoObito = (TextView) findViewById(R.id.txtAnoObito);
    txtMensagemObito = (TextView) findViewById(R.id.txtMensagemObito);
    txtCodigoSituacaoCadastral = (TextView) findViewById(R.id.txtCodigoSituacaoCadastral);
    txtSituacaoRFB = (TextView) findViewById(R.id.txtSituacaoRFB);
    txtDataConsultaRFB = (TextView) findViewById(R.id.txtDataConsultaRFB);
    txtProtocoloRFB = (TextView) findViewById(R.id.txtProtocoloRFB);
    txtDigitoVerificador = (TextView) findViewById(R.id.txtDigitoVerificador);
    txtMensagem = (TextView) findViewById(R.id.txtMensagem);
    txtStatus = (TextView) findViewById(R.id.txtStatus);

    progress = new ProgressDialog(ResultConsCpfActivity.this);
    progress.setTitle("Recebendo Consulta...");
    progress.show();

    //pega os valores dos edittextos
    String email = Email;
    String senha = Senha;

    //chama o retrofit para fazer a requisição no webservice
    retrofitConverter(email, senha, cpf, date);

}

public void setaValores(){

    txtDocumento.setText(resposta.getDocumento());
    txtNome.setText(resposta.getNome());
    txtDataNascimento.setText(resposta.getDataNascimento());
    txtDataInscricao.setText(resposta.getDataInscricao());
    txtAnoObito.setText(resposta.getAnoObito());
    txtMensagemObito.setText(resposta.getMensagemObito());
    txtCodigoSituacaoCadastral.setText(resposta.getCodigoSituacaoCadastral());
    txtSituacaoRFB.setText(resposta.getSituacaoRFB());
    txtDataConsultaRFB.setText((CharSequence) resposta.getDataConsultaRFB());
    txtProtocoloRFB.setText(resposta.getProtocoloRFB());
    txtDigitoVerificador.setText(resposta.getDigitoVerificador());
    txtMensagem.setText(resposta.getMensagem());


}


public void retrofitConverter(String Email, String Senha, String Documento, String DataNascimento) {

    RetrofitService service = ServiceGeneratorCpf.createService(RetrofitService.class);

    Call<RespostaServidorCpf> call = service.mostrarConsultaCpf(Email, Senha, Documento, DataNascimento);

    call.enqueue(new Callback<RespostaServidorCpf>() {
        @Override
        public void onResponse(Call<RespostaServidorCpf> call, Response<RespostaServidorCpf> response) {

            if (response.isSuccessful()) {

                RespostaServidorCpf respostaServidorCpf = response.body();

                //verifica aqui se o corpo da resposta não é nulo
                if (respostaServidorCpf != null) {

                    if(respostaServidorCpf.isValid()) {

                        resposta.setDocumento(respostaServidorCpf.getDocumento());
                        resposta.setNome(respostaServidorCpf.getNome());
                        resposta.setDataNascimento(respostaServidorCpf.getDataNascimento());
                        resposta.setDataInscricao(respostaServidorCpf.getDataInscricao());
                        resposta.setAnoObito(respostaServidorCpf.getAnoObito());
                        resposta.setMensagemObito(respostaServidorCpf.getMensagemObito());
                        resposta.setCodigoSituacaoCadastral(respostaServidorCpf.getCodigoSituacaoCadastral());
                        resposta.setSituacaoRFB(respostaServidorCpf.getSituacaoRFB());
                        resposta.setDataConsultaRFB(respostaServidorCpf.getDataConsultaRFB());
                        resposta.setProtocoloRFB(respostaServidorCpf.getProtocoloRFB());
                        resposta.setDigitoVerificador(respostaServidorCpf.getDigitoVerificador());
                        resposta.setMensagem(respostaServidorCpf.getMensagem());
                        resposta.setValid(respostaServidorCpf.isValid());

                        progress.dismiss();
                        setaValores();

                    } else{

                        Toast.makeText(getApplicationContext(),"Insira unidade e valores válidos", Toast.LENGTH_SHORT).show();
                    }

                } else {

                    Toast.makeText(getApplicationContext(),"Resposta nula do servidor", Toast.LENGTH_SHORT).show();
                }

            } else {

                Toast.makeText(getApplicationContext(),"Resposta não foi sucesso", Toast.LENGTH_SHORT).show();
                // segura os erros de requisição
                ResponseBody errorBody = response.errorBody();
            }

            progress.dismiss();
        }

        @Override
        public void onFailure(Call<RespostaServidorCpf> call, Throwable t) {

            Toast.makeText(getApplicationContext(),"Erro na chamada ao servidor", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);

            progress.dismiss();
        }
    });

}

Look the Json of the webservice i'm trying to request and response: 查看我尝试请求和响应的Web服务的Json:

Json url: http://soawebservices.com.br/restservices/producao/cdc/pessoafisicanfe.ashx 杰森网址: http//soawebservices.com.br/restservices/producao/cdc/pessoafisicanfe.ashx

Please see the link before answer the question! 请先点击链接,然后再回答问题!

How to send the credentials: "Email" "Senha" and receive the Json response? 如何发送凭据:“电子邮件”,“ Senha”并接收Json响应?

What is wrong? 怎么了?

Thanks Guys! 多谢你们!

 Host: soawebservices.com.br POST /restservices/producao/cdc/pessoafisicanfe.ashx Content-Type: application/json { "Credenciais": { "Email": "Seu endereco de E-Mail", "Senha": "Sua Senha" }, "Documento": "999.999.999-99", "DataNascimento": "01/11/2016" } 

So things to note: 所以要注意的是:

  • Retrofit Base URI - API_BASE_URL = "http://www.soawebservices.com.br/"; 加装基本URI- API_BASE_URL = "http://www.soawebservices.com.br/"; (you could add restservices to the end of that...) (您可以在其末尾添加restservices ...)
  • The method type - @POST 方法类型- @POST
  • The address to POST to - "restservices/producao/cdc/pessoafisicanfe.ashx" POST的地址- "restservices/producao/cdc/pessoafisicanfe.ashx"
  • Content-Type - application/json . 内容类型application/json You set this in the @Headers , so that's good. 您在@Headers中进行@Headers ,这样很好。

Now, the message body... 现在,邮件正文...

1) It is not FormUrlEncoded . 1)它不是FormUrlEncoded At least I don't think that's how JSON requests work. 至少我不认为JSON请求是这样工作的。
2) Credenciais is an object itself, the body of the request does not have a flat listing of Email , Senha , Documento , and DataNascimento . 2) Credenciais本身是一个对象,请求的主体没有EmailSenhaDocumentoDataNascimento的平面列表。

Therefore, you need to implement a Credenciais class. 因此,您需要实现一个Credenciais类。

public class Credencials {
    private String Email, Senha;

    public Credencials(String email, String senha) {
        this.Email = email;
        this.Senha = senha;
    }

    // getters, setters...
}

And use that in your interface 并在您的界面中使用它

Call<RespostaServidorCpf> mostrarConsultaCpf(
           @Field("Credencials") Credencials credencials,
           @Field("Documento") String Documento,
           @Field("DataNascimento") String DataNascimento);

Also, use that class 另外,使用该类

RetrofitService service = ServiceGeneratorCpf.createService(RetrofitService.class);

Credencials cred = new Credencials(Email, Senha);

Call<RespostaServidorCpf> call = service.mostrarConsultaCpf(cred, Documento, DataNascimento);

And finally, collapse that if statement. 最后,折叠if语句。

 //verifica aqui se o corpo da resposta não é nulo
 if (respostaServidorCpf != null && respostaServidorCpf.isValid()) {
     resposta = respostaServidorCpf;

     progress.dismiss();
     setaValores();
 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM