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