【问题标题】:HttpUrlConnection PUT method doesn't workHttpUrlConnection PUT 方法不起作用
【发布时间】:2013-03-27 15:06:51
【问题描述】:

我已经使用 AppacheHttpClient 完成了以下客户端应用程序来使用 REST 服务(一种 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 解决方案时一样。我的代码有什么问题?

谢谢。

【问题讨论】:

    标签: java web-services rest httpurlconnection restful-architecture


    【解决方案1】:

    尝试在urlConnection.connect(); 之后调用urlConnection.getResponseCode(); 以强制刷新底层输出流并读取输入流。

    【讨论】:

    • 谢谢!它正在工作!你能告诉我读取响应的操作是什么吗? PUT 方法的结果?
    • 我已经发现了。我必须使用:Scanner inStream = new Scanner(urlConnection.getInputStream());
    • 调用urlconnection.getResponseMessage() 读取与代码关联的HTTP 消息。如果没问题(200+),您可以使用urlconnection.getInputStream()urlconnection.getContent() 读取正文(如果该内容有数据处理程序)。如果您收到错误代码,请使用urlconnection.getErrorStream()
    【解决方案2】:

    尝试设置

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

    之后

    urlConnection.setRequestMethod("PUT");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2014-05-27
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多