我正在寻找一个示例项目,演示如何在不使用现已弃用的HttpClient的情况下将远程JSON对象合并到Android应用程序中。它需要在SDK版本14及更高版本上运行。很难找到任何东西。
非常感谢任何帮助。
谢谢
答案 0 :(得分:0)
尝试使用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);
}