java ASYNCTASK中的HttpUrlConnection && parseJSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java ASYNCTASK中的HttpUrlConnection && parseJSON相关的知识,希望对你有一定的参考价值。
//data store
private void parseJSON(String result) {
ArrayList<HashMap<String, String>> loadData = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> loadDataMap = new HashMap<>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
loadDataMap.put("exh_uid", jsonObject.getString("exh_uid"));
loadDataMap.put("app_uid", jsonObject.getString("app_uid"));
loadData.add(loadDataMap);
}
myGlobalValue.setLoadData(loadData);
} catch (JSONException e) {
e.printStackTrace();
}
}
private ArrayList<HashMap<String, String>> loadData = new ArrayList<>();
public void setLoadData(ArrayList<HashMap<String, String>> loadData) {
this.loadData = loadData;
}
public ArrayList<HashMap<String, String>> getLoadData() {
return loadData;
}
//INNER CLASS
class JobTask2 extends AsyncTask<String, Void, String> {
//
HttpURLConnection urlConnection = null;
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://drupal.udn-device-dept.net/Exhibition/api/getSpecificData.php");
urlConnection = (HttpURLConnection) url.openConnection();
//setRequestMethod:set the method for the URL request.
urlConnection.setRequestMethod("POST");
//Read the response.
//The response body may be read from the stream returned by getInputStream().
urlConnection.setDoInput(true);
//Instances must be configured with setDoOutput(true) if they include a request body.
urlConnection.setDoOutput(true);
//POST method cannot save data to caches, so it need to set usecaches metohod to false.
urlConnection.setUseCaches(false);
// urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
//Create JSONObject here
JSONObject usuario = new JSONObject();
usuario.put("app_uid", "automatic");
usuario.put("get_enroll", "yes");
// Send POST output.
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(usuario.toString());
out.flush();
out.close();
//check urlconnection with response code 200(OK).
int status = urlConnection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
//post request variables.
InputStream is = urlConnection.getInputStream();
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
response.append(line + "\r");
}
reader.close();
return response.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException j) {
Log.d(TAG, "doInBackground: json");
} finally {
//cut the connection.
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
parseJSON(s);
info.setText(s);
//take the {key,value} from getloaddata method and return to store in hashmap.
for (HashMap<String, String> a : myGlobalValue.getLoadData()) {
//store data to list array.
/*List<HashMap<String, String>> test = new ArrayList<>();
test.add(a);
String b = test.toString();*/
info.setText(a.get("app_uid").toString() + "\n" + a.get("exh_uid").toString() + "\n" + a.values());
System.gc();
}
}
}
## HttpUrlConnection
###### Android高效入門-解析JSON資料,使用json.org、Gson、Jackson教學
(https://litotom.com/2016/05/26/android6-json-gson-jackson/)
#### 簡述
Android中发送http网络请求是很常见的,要有GET请求和POST请求。
一个完整的http请求需要经历两个过程:客户端发送请求到服务器,然后服务器将结果返回给客户端。
![](http://img.blog.csdn.net/20160516215923341)
#### HttpClient的一般使用步驟:
1.使用DefaultHttpClient類型實做HttpClient物件
2.創建HttpGet或HttpPost物件,將請求的URL通過建構的方法傳入HttpGet或HttpPost物件
3.調用execute方法發送HTTP GET或HTTP POST請求,並回傳給HttpResponse物件
4.通過HttpResponse接口的getEntity方法取得伺服器回應的訊息,並進行相應的處理
最後記得在AndroidManifest.xml文件添加網路權限
<uses-permission android:name="android.permission.INTERNET" />
#### GET、POST方式的差別:
GET请求可以被缓存。POST请求从不会被缓存。
1.GET是從伺服器上取得數據,POST是向伺服器傳送數據
2.在客戶端,GET方式在通過URL提交數據,數據在URL中可以看到,POST方式數據放在HTML HEADER內提交
3.對於GET方式,伺服器端用Request.QueryString獲取變數的值(值會出現在request header裡)
對於POST方式,伺服器用Request.Form獲取提交的數據(值會在Response Body裡,較具安全性)
4.GET方式提交的數據大於2KB(主要是URL長度限制),而POST則沒有此限制
5.安全性問題,正如差別2.提到,使用GET的時候,參數會顯示在地址欄上,而POST不會,所以如果這些是中文數據而且是非敏感數據,那麼使用GET
如果用戶輸入的數據不是中文字元而且包含敏感數據,那麼還是使用POST數據為好。
//inner class
class JobTask1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// HttpURLConnection & BufferedReader need to declared outside the try/catch.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a String.
String jsonstr = null;
//
try {
//Construct the URL for the backend query.
URL url = new URL("https://video.udn.com/api-cowork/com-app");
//Create the request to backend, and open the connection.
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input Stream into a string.
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonstr = buffer.toString();
} catch (MalformedURLException e) {
Log.d(TAG, "doInBackground: ", e);
} catch (IOException i) {
Log.d(TAG, "doInBackground: ", i);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return jsonstr;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
info.setText(s);
Log.i(TAG, "onPostExecute: ");
}
}
以上是关于java ASYNCTASK中的HttpUrlConnection && parseJSON的主要内容,如果未能解决你的问题,请参考以下文章
从另一个 Activity 类执行 Fragment 中的 AsyncTask 并更新其中的 UI
无法在Asynctask Android,java中调用View
无法在 asyncTask 中的 onPostExecute 中发送消息