【问题标题】:Sending JSON to a server将 JSON 发送到服务器
【发布时间】:2011-01-14 03:26:42
【问题描述】:

我正在运行以下 Java,这是一个 HttpURLConnection PUT 请求,其中包含将从 Android 设备发送的 JSON 数据。在此工作后,我将处理任何引发的异常。 GET 工作正常。

Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(nameString, pwdString.toCharArray());
               }
        });

url = new URL(myURLString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);

urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Content-Type", "application/json");

OutputStream output = null;
try {
  output = urlConnection.getOutputStream();
  output.write(jsonArray.toString().getBytes());
} finally {
  if (output != null) { output.close(); }
}

int status = ((HttpURLConnection) urlConnection).getResponseCode();
System.out.println("" + status);

urlConnection.disconnect();

我收到 HTTP 500 错误(内部错误代码),表示意外属性阻止了请求。 JSONArray 包含我知道其键正确的 JSONObjects。服务器非常标准,需要带有 JSON 主体的 HTTP PUT。

我错过了什么吗?

【问题讨论】:

    标签: android json httpurlconnection


    【解决方案1】:

    首先,我真的建议您使用 Volley,这是一个专门为使用所有请求类型(PUT、DELETE、POST、GET)的 HTTP(s) 请求开发的谷歌 API。 我推荐你看这个:Video from Google I/O 并遵循本教程(涵盖您的问题):Tutorial Link

    如果您决定试一试,请告诉我,我很乐意为您提供帮助!

    再见!

    【讨论】:

    • 感谢您的建议。这个问题已经很老了,事情已经发生了变化。我自从使用 Volley 或 Picasso。
    猜你喜欢
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多