1

我已經做了以下的客戶端應用程序消耗REST服務(一PUT方法)使用AppacheHttpClient(它的工作):HttpURLConnection的PUT方法不起作用

public class UserLogin { 

    private static final String URL = "http://192.168.1.236:8080/LULServices/webresources"; 

    public static void main(String[] args) throws Exception { 

    final DefaultHttpClient httpclient = new DefaultHttpClient(); 

    try { 
      httpclient.getCredentialsProvider().setCredentials(
       new AuthScope("localhost", 8080), 
       new UsernamePasswordCredentials("xxxxx", "xxxxx")); 

    HttpPut httpPut = new HttpPut(URL + "/services.users/login"); 
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); 

    httpPut.addHeader("Content-type", "multipart/form-data"); 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("login", "xxxxx")); 
    nameValuePairs.add(new BasicNameValuePair("password", "xxxxx")); 

    httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    HttpResponse response = httpclient.execute(httpPut); 

    try { 
      HttpEntity entity = response.getEntity(); 
      String putResponse = EntityUtils.toString(entity); 
      System.out.println("Login successful! Secret id: " + putResponse); 
      EntityUtils.consume(entity); 

     } finally { 
      httpPut.releaseConnection(); 
     } 

     } finally { 
      httpclient.getConnectionManager().shutdown(); 
     } 
    } 
} 

現在我想這樣做使用HttpURLConnection的,但不工作:

public class PUTmethod { 

    public static void main(String[] args) throws Exception 
    { 
     HttpURLConnection urlConnection = null; 

    try { 
     String webPage = "http://localhost:8080/LULServices/webresources/services.users/login"; 

       Authenticator myAuth = new Authenticator() 
       { 
        final static String USERNAME = "xxxxx"; 
        final static String PASSWORD = "xxxxx"; 

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

       Authenticator.setDefault(myAuth); 

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

       urlConnection.setReadTimeout(10000); 
       urlConnection.setConnectTimeout(15000); 
       urlConnection.setRequestMethod("PUT"); 
       urlConnection.setRequestProperty("Content-type", "multipart/form-data"); 
       urlConnection.setDoOutput(true); 
       urlConnection.setDoInput(true); 

       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       nameValuePairs.add(new BasicNameValuePair("login", "xxxxx")); 
       nameValuePairs.add(new BasicNameValuePair("password", "xxxxx")); 

       OutputStream out = urlConnection.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); 
       writer.write(getQuery(nameValuePairs)); 
       writer.close(); 
       out.close(); 

       urlConnection.connect(); 

    } catch (MalformedURLException e) { 
      e.printStackTrace(); 
    } catch (IOException e) { 
      System.out.println("Failure processing URL"); 
      e.printStackTrace(); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
     finally { 
     if (urlConnection != null) { 
      urlConnection.disconnect(); 
     } 
    } 
    } 
public static 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")); 
     } 
     System.out.println(result.toString()); 
     return result.toString(); 
    }   
} 

如果不工作,我的意思是說沒有出現任何錯誤,但PUT不起作用,就像當我使用ApacheHttpClient解決方案。我的代碼有什麼問題?

謝謝。

回答

1

嘗試在urlConnection.connect();之後調用urlConnection.getResponseCode();強制刷新底層輸出流並讀取輸入流。

+0

謝謝!它正在工作!你能告訴我什麼操作來讀取響應? PUT方法的結果? – user2144555 2013-03-27 15:29:27

+0

我已經發現。我必須使用:'Scanner inStream = new Scanner(urlConnection.getInputStream());' – user2144555 2013-03-27 15:33:42

+0

調用'urlconnection.getResponseMessage()'來讀取與代碼相關的HTTP消息。如果它是一個OK(200+),則可以使用'urlconnection.getInputStream()'或'urlconnection.getContent()'來讀取主體,如果該內容有數據處理程序。如果您收到錯誤代碼,請使用'urlconnection.getErrorStream()' – 2013-03-27 15:33:57

0

儘量設置

urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); 

urlConnection.setRequestMethod("PUT");