[Android] 使用HttpGet加上基本驗證時,得到回應400 Bad Request
在Android的開發上,搭配Restful Service去取得資料時,通常會使用HttpClient加上HttpGet去向Server抓取資料來源,例如說下面這樣 try { HttpResponse response = client.execute(get); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpStatus.SC_OK){ HttpEntity entity = response.getEntity(); ByteArrayOutputStream out = new ByteArrayOutputStream(); entity.writeTo(out); out.close(); result = out.toString(); } } catch (IOException ex){ result = null; } 而在Restful Service的安全性上面,驗證方式通常會採用基本驗證(在header中加入驗證資訊)加上https來做(這篇不會提到https的部分);而加入驗證資訊的部分會像是這樣的方式 String encoding = Base64.encodeToString((userName+":"+userPwd).getBytes(), Base64.NO_WRAP ); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(requestUrl); get.addHeader("Authorization","Basic "+encoding);