步骤一:定义回调接口
package com.qtechnix.QuarkHq;
public interface AsyncResponse { void onDataReceivedSuccess(String jsonCommand, String resultJson); void onDataReceivedFailed(String jsonCommand); }
|
步骤二:http json 定义
package com.qtechnix.QuarkHq;
import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.StrictMode; import android.util.Log; import android.widget.ListView; import android.widget.Toast;
import com.google.gson.Gson; import com.google.gson.FieldNamingPolicy;
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Set;
public class HttpJson extends AsyncTask<String, Void, Void> {
private String _jsonResult; private String _jsonCommand; private Context _parentContext; private AsyncResponse _asyncResponse;
public HttpJson(Context context) { _parentContext = context; }
public void setAsyncResponse(AsyncResponse asyncResponse) { this._asyncResponse = asyncResponse; }
@Override protected Void doInBackground(String... arg) { /* String domain = ""; String member_req_token_url = ""; // read responseURLEncoder.encode(para, "GBK"); String urlWithParams = domain + member_req_token_url + "?userName=" + java.net.URLEncoder.encode(params[0], "utf-8") + "&password=" + params[1]; URL url = new URL(urlWithParams); */
_jsonCommand = arg[2]; _jsonResult = doReq(arg[0], arg[1], _jsonCommand); return null; }
@Override protected void onPreExecute() { super.onPreExecute(); }
@Override protected void onPostExecute(Void aVoid) { Log.e("gmx onPostExecute:", _jsonResult); if (_jsonResult == null) { _asyncResponse.onDataReceivedFailed(_jsonCommand); } else { _asyncResponse.onDataReceivedSuccess(_jsonCommand, _jsonResult); } super.onPostExecute(aVoid); }
public String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "/n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
//method = "GET" | "POST" | "PUT"; public String doReq(String urlStr, String method, String apiName) { InputStream inputStream = null; HttpURLConnection httpConn = null; try { System.out.println("gmx:" + urlStr); URL url = new URL(urlStr);
System.out.println("gmx: to create connection"); httpConn = (HttpURLConnection) url.openConnection(); //optional request header httpConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //optional request header httpConn.setRequestProperty("Accept", "application/json"); // for Get request httpConn.setRequestMethod(method); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); httpConn.setConnectTimeout(3000); httpConn.setReadTimeout(3000);
System.out.println("gmx: to connect"); httpConn.connect(); DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream()); System.out.println("gmx: to new gson"); Gson gs = new Gson(); Map<String, String> dto = new HashMap<String, String>(); dto.put("command", apiName); System.out.println("gmx:to invoke toJson()"); String jsonString = gs.toJson(dto); System.out.println(jsonString); wr.writeBytes(jsonString); wr.flush(); wr.close(); System.out.println("gmx:to get response"); int statusCode = httpConn.getResponseCode(); // 200 represents HTTP OK if (statusCode == 200) { inputStream = new BufferedInputStream(httpConn.getInputStream()); String str = convertStreamToString(inputStream); str = str.substring(0, str.length() - 1); return str; } else { System.out.println("gmx: error not 200"); } } catch (Exception e) { Log.e("gmx", "error : ", e); System.out.println("gmx: Exception"); e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (httpConn != null) { httpConn.disconnect(); } } return null; } }
|
步骤三:调用及分析返回(Main Activity)
HttpJson js = new HttpJson(MainActivity.this); js.execute("http://192.168.0.23:7979", "POST", "get_runtime_info"); js.setAsyncResponse(new AsyncResponse() { @Override public void onDataReceivedSuccess(String jsonCommand, String jsonResult) { Log.d("gmx jsonResult", jsonResult);
//do anything such as, something = gson.fromGgson(jsonResult,CLASS); ...
} @Override public void onDataReceivedFailed(String jsonCommand) { Log.e("gmx", "data received failed!"); } });
|