Android:进行REST调用的问题

时间:2016-06-08 12:12:19

标签: java android rest http retrofit

我使用Java开发了一个REST API,实现了Jersey。现在我正在尝试连接我的Android应用程序。

下面的代码与我的REST API有关。

PatientJSONService

import bean.PatientBean;
import bean.UserBean;
import db.PatientImpl;
import db.PatientInterface;
import db.UserImpl;
import db.UserInterface;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/patient")
public class PatientJSONService 
{
    @POST
    @Path("/insertPatient")
    @Consumes(MediaType.APPLICATION_JSON)
    public String insertPatient(PatientBean bean)
    {
        System.out.println("Printed");
        PatientInterface patientInterface = new PatientImpl();
        String insertUser = patientInterface.insertPatient(bean);
        return insertUser;
    }

    @GET
    @Path("/getAllPatients")
    @Produces(MediaType.APPLICATION_JSON)       
    public List<PatientBean> getAllPatients()
    {
        PatientInterface patinetInterface=new PatientImpl();
        List<PatientBean> allPatients = patinetInterface.getAllPatients();

        return allPatients;
    }

    @POST
    @Path("/getPatientById/{id}")
    @Produces(MediaType.APPLICATION_JSON)       
    public PatientBean getPatientByFlareId(@PathParam("id")String flareId)
    {
        PatientInterface patinetInterface=new PatientImpl();
        PatientBean patientById = patinetInterface.getPatientById(id);
        return patientById;
    }

}

PatientBean

public class PatientBean {

    private int idPatient;
    private String id;

    public int getIdPatient() {
        return idPatient;
    }

    public void setIdPatient(int idPatient) {
        this.idPatient = idPatient;
    }

    public String getID() {
        return flareID;
    }

    public void setID(String id) {
        this.id = id;
    }

}

PatientImpl - (数据库类)

public class PatientImpl implements PatientInterface {

    @Override
    public String insertPatient(PatientBean patientBean) 
    {
        String sql = "INSERT INTO patient (id) values(?)";
        String result="";

        Connection con = null;
        PreparedStatement ps = null;

        try
        {
            con = DBMaster.getInstance().getConnection();
            con.setAutoCommit(false);
            ps = con.prepareStatement(sql.toLowerCase());

            ps.setString(1,patientBean.getID());

            ps.executeUpdate();
            con.commit();
            result = Common.SUCCESS;
        }
        catch(Exception e)
        {
            try
            {
                con.rollback();
                e.printStackTrace();
                result = Common.ROLLBACK;
            } 
            catch (SQLException ex)
            {
                ex.printStackTrace();
                result = Common.ROLLBACK_FAILED;
            }
        }
        finally
        {
            try
            {
                ps.close();
                con.close();
            } catch (SQLException ex)
            {
                ex.printStackTrace();
            }
        }

        System.out.println(result);
        return result;   
    }
}

现在,您对REST API的外观有了清晰的认识。让我们看看我如何编程我的Android应用程序来访问此API。在这里,我实际上正在使用retrofit 2 - http://square.github.io/retrofit/

MainActivity

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import bean.Common;
import bean.PatientBean;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    public static final String URL = "http://x.x.x.x:8080/TestRest/rest/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        restCall();
    }

    @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 boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void restCall()
    {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        YourEndpoints request = retrofit.create(YourEndpoints.class);

        PatientBean patientBean= new PatientBean ();
        patientBean.setId(SLKRT0065);

        Call<ResponseBody> yourResult = request.insertPatient(patientBean);
        yourResult.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                try {
                    Log.d("MainActivity", "RESPONSE: " + response.body().string());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                try {
                    t.printStackTrace();
                    Log.d("MainActivity", "RESPONSE: "+"FAILED");
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

        });
    }
}

从上面的课程中,看一下发生REST调用的方法restCall()

YourEndpoints

public interface YourEndpoints {

    @POST("patient/insertPatient")
    Call<ResponseBody> insertPatient(@Body PatientBean patientBean);
}

我不知道我做错了什么,但它根本没有用。当我运行此代码时,我在此处NULLPOINTERException得到一个Log.d("MainActivity", "RESPONSE: " + response.body().string());,这意味着响应可能为null /如果我删除该部分代码运行正常,但我在数据库中看不到任何内容。

我该如何解决这个问题?

0 个答案:

没有答案