2013-03-14 54 views
1

我开发了REST服务泽西岛,这是从MySQL DB生成的。我可以从Web服务页面(URL)的数据库中/从/中获取信息。 现在我开发一个客户端应用程序,安全。我有能力从数据库做一个GET,但我怎么能更新它?随着PUT方法 ...如何从REST客户端应用程序更新MySQL数据库?

感谢

还有就是我的经历都与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(); 
      } 
      } 
     } 
    } 
} 

谢谢!

回答

2

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

你也许可以找到更高水平的REST客户端API,而是应的HTTPClient是非常简单的使用。

+0

你知道,一个好的教程?它更简单吗? – user2144555 2013-03-14 11:01:08

+0

这里有一个[快速启动(http://hc.apache.org/httpcomponents-client-ga/quickstart.html)。您也可以在项目网站上找到更多深入的教程。 – NilsH 2013-03-14 11:12:02

+0

我想我会按照你的意见,一旦你不是第一个告诉我!我只是在选择一个选项之前尝试一些选项,因为我对这个主题不太了解。 – user2144555 2013-03-14 11:19:01