從非ui線程調用以下方法並傳遞url和body內容。在doInBackground方法中使用AsyncTask並調用以下方法。
class BackgroundTask extends AsyncTask<Void,Void,String>{
@Override
protected String doInBackground(Void... voids) {
String url = "http://teespire.com/ptracking/post/index.php?tag=GetDeviceInfo";
String body = "{ \"did\": \"1\" }";
return excutePost(url,body);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
try {
JSONObject jsonObject = new JSONObject(result);
int status = jsonObject.getInt("status");
JSONObject dataObject = jsonObject.getJSONObject("data");
String displayName = dataObject.getString("displayname");
//do your stuff here
}catch (JSONException e){
e.printStackTrace();
}
}
}
}
public String excutePost(String targetURL, String body)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes (body);
wr.flush();
wr.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}else{
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
我認爲這對你有幫助。
[讓我爲你谷歌](https://developer.android.com/training/volley/index.html) – n00dl3
你應該檢查這個網站http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ 它已經詳細解釋了該做什麼以及如何做一步明智。 – am110787