Java 如何在Android中调用'POST`RESTfull方法?

Java 如何在Android中调用'POST`RESTfull方法?,java,android,rest,http,post,Java,Android,Rest,Http,Post,我用Java开发了一个web服务。下面是一个方法 @Path("/setup") public class SetupJSONService { @POST @Path("/insertSetup") @Consumes(MediaType.APPLICATION_JSON) public String insertSetup(SetupBean bean) { System.out.println("Printed");

我用Java开发了一个web服务。下面是一个方法

@Path("/setup")
public class SetupJSONService {

    @POST
    @Path("/insertSetup")
    @Consumes(MediaType.APPLICATION_JSON)
    public String insertSetup(SetupBean bean)
    {
        System.out.println("Printed");
        SetupInterface setupInterface = new SetupImpl();
        String insertSetup = setupInterface.insertSetup(bean);
        return insertSetup;
    }
}
下面是我如何在我的计算机中使用Java
Jersey
调用此方法

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/TestApp/rest/setup").path("/insertSetup");

SetupBean setupBean = new SetupBean();
setupBean.setIdPatient(1);
setupBean.setCircleType(1);

target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(setupBean, MediaType.APPLICATION_JSON_TYPE));
然而,现在这个方法也应该在Android中调用,但我不知道如何做到这一点。我知道如何在android中进行
GET
调用,如下所示

public static String httpGet(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn =
      (HttpURLConnection) url.openConnection();

  if (conn.getResponseCode() != 200) {
    throw new IOException(conn.getResponseMessage());
  }

  // Buffer the result into a string
  BufferedReader rd = new BufferedReader(
      new InputStreamReader(conn.getInputStream()));
  StringBuilder sb = new StringBuilder();
  String line;
  while ((line = rd.readLine()) != null) {
    sb.append(line);
  }
  rd.close();

  conn.disconnect();
  return sb.toString();
}

但是,既然我的方法是
POST
,而且它接受
javabean
,并返回
字符串,那么在Android中我该如何处理这个问题呢?我对在android中使用Jersey不感兴趣,因为它在android环境中确实有不好的评论。

android提供了一种做你想做的事情的方法,但这不是一种有效的方法,我喜欢使用改型2来推动我的开发并编写更好的代码

下面是一个可以帮助您的改装2示例=):

添加到build.gradle中的依赖项

dependencies {
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'  
}
创建指定转换器和基本url的改装生成器

public static final String URL = "http://localhost:8080/TestApp/rest/";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
现在创建一个接口来封装rest方法,如下所示

public interface YourEndpoints {
    @POST("setup/insertSetup")
    Call<ResponseBody> insertSetup(@Body SetupBean setupBean);
}
端点的公共接口{
@POST(“设置/插入设置”)
调用insertSetup(@Body SetupBean SetupBean);
}
将端点接口与改装实例相关联

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

Call<ResponseBody> yourResult = request.insertSetup(YourSetupBeanObject);
    yourResult.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            //response.code()
            //your string response response.body().string()
        }

        @Override
        public void onFailure(Throwable t) {
            //do what you have to do if it return a error
        }
    });
YourEndpoints请求=改装.create(YourEndpoints.class);
调用yourResult=request.insertSetup(YourSetupBeanObject);
yourResult.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
//响应代码()
//您的字符串响应response.body().string()
}
@凌驾
失效时的公共无效(可丢弃的t){
//如果它返回错误,请执行您必须执行的操作
}
});
有关更多信息,请参阅此链接:


这是你想要的正常方式的代码

InputStream is = null;
        OutputStream os = null;
        HttpURLConnection con = null;
        try {
            //constants
            URL url = new URL("http://localhost:8080/TestApp/rest/");
           //Map your object to JSONObject and convert it to a json string
            String message = new JSONObject().toString();

            con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(1000);
            con.setConnectTimeout(15000);
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setFixedLengthStreamingMode(message.getBytes().length);

            con.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //open
            con.connect();

            //setup send
            os = new BufferedOutputStream(con.getOutputStream());
            os.write(message.getBytes());
            //clean up
            os.flush();

            //do somehting with response
            is = con.getInputStream();
            String contentAsString = readData(is,len);

            os.close();
            is.close();
            con.disconnect();
        } catch (Exception e){
            try {
                os.close();
                is.close();
                con.disconnect();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

谢谢你的来信。但为什么不能用正常的内在事物来实现呢?这样做似乎太过分了。不客气=),你可以用正常的方式来做!我只想指出一种更高效、更易于使用的方法谢谢。有正常方式的指导吗?我认为在Jersey,在发送到服务器之前,他们也会在内部将对象转换为JSON?下面用heheThanks的正常方式回答。在这个答案中,请问“YourEndPoint”是什么?谢谢。我认为Gson可以将对象转换为jsonYes,您可以使用Gson=)Gson g=new Gson();字符串json=g.toJson(YourObject);正如您所看到的,在服务器端,我的应用程序正在接受JavaBean。那么这个wotk会吗?嗨,两个小时后都会试试。现在已经是午夜了:我真的很感谢你的持续支持,很快就会告诉你最新情况。