Post JSON 数据并在 android 中接收响应

Post JSON data and receive response in android

我想 post 简单地 JSON 网络服务并接收响应,但我在 client.getResponseCode()

上收到 java.io.IOException : No authentication challenges found 错误

我尝试了 this solution 但它对我不起作用。

这是我的代码:

StringBuilder sb = new StringBuilder();
HttpURLConnection client = null;

try {
     URL url = new URL("http://myurl:3000");
     client = (HttpURLConnection) url.openConnection();
     client.setDoOutput(true);
     client.setDoInput(true);
     client.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
     client.setRequestProperty("Authorization", "Basic " + Base64.encodeToString("userid:pwd".getBytes(), Base64.NO_WRAP));
     client.setRequestMethod("POST");

     client.connect();

     OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
     String output = json.toString();
     writer.write(output);
     writer.flush();
     writer.close();

     int HttpResult = client.getResponseCode();
     if (HttpResult == HttpURLConnection.HTTP_OK) {
         BufferedReader br = new BufferedReader(new InputStreamReader(
                            client.getInputStream(), "utf-8"));
         String line = null;
         while ((line = br.readLine()) != null) {
               sb.append(line + "\n");
         }
         br.close();
     }
} catch (IOException e) {
  this.e = e;
} finally {
  client.disconnect();
}

我认为如果您尝试使用 OkHttp,Square 开发人员为 Android 开发的 HTTP 客户端,您会取得更大的成功。它添加了一个抽象层,因此您不必为一个简单的 POST 请求编写那么多代码。以下是 POST 向服务器请求的代码示例:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

(我会将其添加为评论,但我还没有 SO 代表)

试试这个例子来编码用户名密码

  username = mUsername.getText().toString();
            password = mPassword.getText().toString();
            mResult.setText(username + ":" + password);
            mCombination = username + ":" + password;
            byte[] byteArray = new byte[0];
            try {
                byteArray = mCombination.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            final String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
            mEncoded.setText(base64);

您确定服务器站点上有有效的 android 令牌吗?这只是一个随机的想法,但我前段时间遇到过类似的问题;)