2014年8月14日 星期四

HttpAsyncTask

public class HttpAsyncTask extends AsyncTask<String, Void, String> {

    /** The m context. */
    private Context mContext;
   
    /** The m fragment callback. */
    private FragmentCallback mFragmentCallback;//1
   
   
    /**
     * Instantiates a new http async task.
     *
     * @param context the context
     * @param fragmentCallback the fragment callback
     */
    public HttpAsyncTask(Context context , FragmentCallback fragmentCallback) {
        mContext = context;
        mFragmentCallback = fragmentCallback;
    }


    @Override
    protected String doInBackground(String... params) {
        try{
            return JsonUtils.POST(params[0], params[1]);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject json = new JSONObject(result);

            mFragmentCallback.onTaskDone(json);
           
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}




public class JsonUtils {

    /**
     * String convert to json object.
     *
     * @param value the value
     * @return the JSON object
     */
    public static JSONObject stringConvertToJsonObject(String value) {
        JSONObject object = null;
        try {
            object = new JSONObject(value);
        } catch (Exception e) {
            // TODO: handle exception
        }
       
        return object;
       
    }
   

   
    /**
     * Post.
     *
     * @param url the url
     * @param json the json
     * @return the string
     */
    public static String POST(String url, String json) {
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            //Log.d("JsonUtils POST json.toString()", json.toString());
            // ** Alternative way to convert Person object to JSON string usin
            // Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);

            // 5. set json to StringEntity

            StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the
            // content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            // httpPost.setHeader("user-agent", "Java/1.7.0_17");
            // httpPost.setHeader("connection", "keep-alive");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 11. return result
        Utils.myLog(result);
       
           

        return result;
    }

    /**
     * Convert input stream to string.
     *
     * @param inputStream the input stream
     * @return the string
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
}

沒有留言:

張貼留言