1

我在Jersey开发了REST 服务,这些服务是从MySQL DB生成的。我能够从 Web 服务页面 (URL) 获取/放入数据库中的信息。现在我正在为此开发一个具有安全性的客户端应用程序。我能够从数据库中获取 GET,但我该如何更新它?使用PUT 方法...

谢谢

我有两种使用 GET 的经验(第一个使用HttpBasicAuthFilter的安全性,第二个使用HttpURLConnection):

        public class BasicAuthenticationClient {

        public static void main(String[] args) {
            ExampleResourceClient erc = new ExampleResourceClient();
            erc.setUsernamePassword("blive1", "KPsS2");
            System.out.println(erc.getMessage());
            erc.close();
        }

        static class ExampleResourceClient {

        private com.sun.jersey.api.client.WebResource webResource;
        private com.sun.jersey.api.client.Client client;
        private static final String BASE_URI = http://localhost:8080/LULServices/webresources";

        public ExampleResourceClient() {
        com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
        client = com.sun.jersey.api.client.Client.create(config);
        client.addFilter(new LoggingFilter());
        webResource = client.resource(BASE_URI).path("entities.user");
        }

        public String getMessage() throws com.sun.jersey.api.client.UniformInterfaceException {
        WebResource resource = webResource;
        return resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(String.class);
        }

        public void putMessage(Object requestEntity) throws com.sun.jersey.api.client.UniformInterfaceException {
                webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(requestEntity);
        }

        public void close() {
        client.destroy();
        }

        public void setUsernamePassword(String username, String password) {
        client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, password));
        }
     }
 }

public class GETurlConnectionClient {

    public static void main(String[] args) throws Exception
    {
        new GETurlConnectionClient();
    }

    public GETurlConnectionClient()
    {
        HttpURLConnection urlConnection = null;

    try {
        String webPage = "http://localhost:8080/LULServices/webresources/entities.userview";
            String name = "blive2";
        String password = "microio";

            Authenticator myAuth = new Authenticator() 
            {
             final String USERNAME = "blive1";
             final String PASSWORD = "KPsS2";

             @Override
             protected PasswordAuthentication getPasswordAuthentication()
             {
              return new PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
             }
            };

            Authenticator.setDefault(myAuth);

            String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

           URL urlToRequest = new URL(webPage);
           urlConnection = (HttpURLConnection) urlToRequest.openConnection();

           urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
           System.out.println("Authorization : Basic " + authStringEnc);

           Map<String, List<String>> hf = urlConnection.getHeaderFields();
           for (String key : hf.keySet())
           System.out.println(key + ": " + urlConnection.getHeaderField(key));

           // Display request method, responde code and response message
           System.out.println("Request method is " + urlConnection.getRequestMethod());
           System.out.println("Response code is " + urlConnection.getResponseCode());
           System.out.println("Response Message is " + urlConnection.getResponseMessage());

           // Display the content
           String results = doHttpUrlConnectionAction(webPage);
           System.out.println(results);

    } catch (MalformedURLException e) {
            e.printStackTrace();
    } catch (IOException e) {
            System.out.println("Failure processing URL: " + "http://localhost:8080/LULServices/webresources");
            e.printStackTrace();
    } catch (Exception e) {
            // deal with the exception in your "controller"
        }

        finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
     }
    // Read the content 
    private String doHttpUrlConnectionAction(String webPage)
    throws Exception
    {
        URL url = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder;

        try
        {
            // create the HttpURLConnection
            url = new URL(webPage);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");

            // Reading from a URLConnection (not display yet)
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)  {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();

        }   catch (Exception e)     {
                e.printStackTrace();
                throw e;
            }

        finally
        {
            // close the reader; this can throw an exception too, so wrap it in another try/catch block.
            if (reader != null) {
                try {
                    reader.close();
                }
            catch (IOException ioe) {
                ioe.printStackTrace();
            }
            }
        }
    }
}

谢谢!

4

1 回答 1

2

我建议您考虑使用更高级别的 API,例如Apache HTTPClient ,而不是使用 URLConnections 和 HTTP 连接中发生的所有低级别的东西

您可能可以找到更高级别的 REST 客户端 API,但 HTTPClient 应该非常易于使用。

于 2013-03-14T10:54:52.030 回答