我想使用用户名和密码调用安全的 rest api (Https)。来自 api 的响应是 JSON 对象。
我怎样才能做到这一点 ?
谢谢你。
对于连接使用 AsyncTask 和这个片段:
URL url = new URL(res.getString(R.string.url));
String charset = res.getString(R.string.utf);
HttpURLConnection http = null;
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
http = https;
http.setRequestMethod(res.getString(R.string.post));
http.setDoInput(true);
http.setDoOutput(true);
http.setRequestProperty(res.getString(R.string.charset), charset);
http.setRequestProperty(res.getString(R.string.content_type), "application/x-www-form-urlencoded;charset=" + charset);
String query = String.format("par1=%s&par2=%s&par3=%s&par4=%s",
URLEncoder.encode(res.getString(R.string.par), charset),
URLEncoder.encode(res.getString(R.string.par2), charset),
URLEncoder.encode(res.getString(R.string.par3), charset),
URLEncoder.encode(holder.toString(), charset));
OutputStream output = null;
try {
output = http.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()),4800);
StringBuffer responseBuffer = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
responseBuffer.append(line);
}
in.close();
answer = new Gson().fromJson(responseBuffer.toString(), Answer.class);
对于解析 JSON 对象,请使用 Google 制作的 GSON 库,非常有帮助。
对请求使用 HTTPPost 对象,对响应使用 JSONObject。例如 :
http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/