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

时间:2016-06-07 11:33:59

标签: 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");
        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,并且因为它接受了Java Bean并且确实返回了String,我该如何在Android中处理此问题?不感兴趣在Android中使用Jersey,因为它在Android环境中有不好的评论。

2 个答案:

答案 0 :(得分:5)

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();

现在创建一个接口,它将封装您的其余方法,如下所示

public interface YourEndpoints {
    @POST("setup/insertSetup")
    Call<ResponseBody> 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
        }
    });

参考此链接以获取更多信息:

http://square.github.io/retrofit/

https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit

答案 1 :(得分:2)

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

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();
            }

        }