Wie zum senden von Abfrage-Parameter an POST-Anforderung von der Java-client, und erhalten mit @QueryParam

Ich versuche zu schreiben, die eine grundlegende web-service, verwendet JAX-RS @QueryParam annotation. Meine Java-client sendet eine POST-Anforderung mit HttpURLConnection. Der Anruf wird an das web-service, aber die Parameter sind nicht immer richtig geschickt (Sie bleiben null). Ich weiß es sind viele Fragen auf StackOverflow, aber ich konnte nicht finden eine überzeugende Lösung. Es wäre toll, wenn jemand darauf hinweist, die Fehler im code unten.
(Ich habe das vereinfacht den code für das posting hier).

Hier ist die web-service-code:

@POST
@Path("/notify")
@Consumes("*/*")
public Response notifyUser(@QueryParam("notification") String notification, @QueryParam("applicationName") String applicationName) {
    System.out.println("Notification: " + notification);
    System.out.println("Application: " + applicationName);
    return Response.status(200).entity(notification + " from " + applicationName).build();
}

- Und das ist Java-client:

public static void main(String args[]) {
    URL url;
    HttpURLConnection conn = null;
    try {
         url = new URL("http://localhost:8080/...");
         conn = (HttpURLConnection) url.openConnection();
         conn.setDoOutput(true);
         conn.setRequestMethod("POST");
         conn.setDoInput(true);
         conn.setDoOutput(true);
         conn.setRequestProperty("Content-Type", "application/json");
         conn.setRequestProperty("charset", "UTF-8");
         OutputStream os = conn.getOutputStream();
         List<NameValuePair> params = new ArrayList<NameValuePair>();
         params.add(new NameValuePair("notification", "Notification string"));
         params.add(new NameValuePair("applicationName", "MyApp"));
         os.write(getQuery(params).getBytes("UTF-8"));
         os.flush();
         os.close();
         return conn.getResponseCode();
    } catch (Exception e) {
        //TODO Auto-generated catch block
        e.printStackTrace();
        return -1;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

Meine web-service wird immer aufgerufen, aber die Werte der parameter erhalten werden, die als null. Bitte helfen Sie.

Ist dieser code nur für Android-JDK oder für die Windows-JDK?

InformationsquelleAutor Akhil Dixit | 2016-03-04

Schreibe einen Kommentar