我創建一個RESTful Web服務:請求寧靜與POJO對象和方法後網絡服務
@POST
@Path("grd")
@Consumes("application/json")
@Produces("text/plain")
public String guardarDato(PostParams jsonObject) {
/*
something here
}
PostParams是一個POJO:
public class PostParams {
private final Map<String, String> postParamsList;
public PostParams() {
postParamsList = new HashMap<>();
}
public void addParameter(String name, String value) {
postParamsList.put(name, value);
}
public String getPostParamsList(String name) {
return postParamsList.get(name);
}
public void getPostParamsMap() {
if (postParamsList.isEmpty()) {
System.out.println("Parametros vacios");
} else {
for (String key : postParamsList.keySet()) {
System.out.println("Clave: " + key + " -> Valor: " + postParamsList.get(key));
}
}
}
}
我想打電話給在Android這個Web服務與HttpUrlConnection, 但我的對象是空的pojo在我的Web服務。
try {
URL url = new URL("http://localhost:8080/VfqCh/hgt/opli/grd");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
// conn.setRequestProperty("Accept", "application/json");
PostParams postParams = new PostParams();
postParams.addParameter("h", "51rt3");
postParams.addParameter("x", "dsfsd8698sdfs");
postParams.addParameter("ax", "Dairon");
postParams.addParameter("tf", "D");
// String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
Gson gson = new Gson();
String gString = gson.toJson(postParams, PostParams.class);
try (OutputStreamWriter printout = new OutputStreamWriter(conn.getOutputStream())) {
printout.write(gString);
printout.flush();
}
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
該信息發送到Web服務,但對象爲空。 如果我改變對象的類型,它是接收Web服務,如果它工作!:
@POST
@Path("grd")
@Consumes("application/json")
@Produces("text/plain")
public String guardarDato(String jsonObject) {
/*
something here
}
但我需要在Web服務中得到的對象!有可能的?
你做了一個簡單的Hashmap的POJO? –
[從Android發送JSON HTTP POST請求]可能的重複(http://stackoverflow.com/questions/13911993/sending-a-json-http-post-request-from-android) –
是的,是一個pojo一個hashmap。 –