簡體   English   中英

發布JSON數據並在android中接收響應

[英]Post JSON data and receive response in android

我想將簡單的JSON發布到Web服務並接收響應,但是我正在獲取java.io.IOException : No authentication challenges found client.getResponseCode()client.getResponseCode() java.io.IOException : No authentication challenges found錯誤

我嘗試了此解決方案,但對我不起作用。

這是我的代碼:

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();
}

試試這個例子來編碼用戶名密碼

  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);

我認為,如果嘗試使用由Square開發人員制作的Android的HTTP客戶端OkHttp ,您將獲得更大的成功。 它增加了一層抽象,因此您不必為一個簡單的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代表)

您確定服務器站點上有有效的android令牌嗎? 這只是一個隨機的想法,但前一段時間我也遇到過類似的問題;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM