1
我正在尋找一個示例項目,演示如何將遠程JSON對象合併到android應用程序中,而不使用現在已棄用的HttpClient。它需要在SDK 14及更高版本上工作。它很難找到任何東西。Android JSON沒有棄用HttpClient
任何幫助,非常感謝。
謝謝
我正在尋找一個示例項目,演示如何將遠程JSON對象合併到android應用程序中,而不使用現在已棄用的HttpClient。它需要在SDK 14及更高版本上工作。它很難找到任何東西。Android JSON沒有棄用HttpClient
任何幫助,非常感謝。
謝謝
嘗試使用HttpURLConnection代替。
HttpURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(CONN_TIMEOUT * 1000);
conn.setReadTimeout(READ_TIMEOUT * 1000);
conn.setRequestMethod(POST);
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject job = new JSONObject();
job.put("id", "asdf");
job.put("pw", "asdf");
os = conn.getOutputStream();
os.write(job.toString().getBytes());
os.flush();
String response;
int responseCode = conn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[1024];
byte[] byteData = null;
int nLength = 0;
while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
response = new String(byteData);
JSONObject responseJSON = new JSONObject(response);
Boolean result = (Boolean) responseJSON.get("result");
String age = (String) responseJSON.get("age");
String job = (String) responseJSON.get("job");
Log.i(TAG, "DATA response = " + response);
}