如何使用async从隔离的类中发出HttpRequest发布的OK?

时间:2016-10-28 05:33:28

标签: java android class okhttp3 okhttp

我在另一个地方使用它作为异步,但我想重构以使其可重用,我如何重新组织代码以便作为消耗类工作?如果它不是异步并且后端的ip被很好地定义,它就不起作用,所以它不是那样的。有什么想法吗?

public class HTTPRequestManager {

    public static JSONArray fetchData(){


        return null;

    }

    public static String postData(Context context, String url, String JSONData)  {




            return null;
    }

   /* @Override
    protected Integer doInBackground(String... strings) {

        try {
            //1.create client Object
            OkHttpClient client = new OkHttpClient();
            //2.Define request being sent to server
            RequestBody postData = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONData);
            Request request = new Request.Builder()
                    .url(context.getResources().getString(R.string.backend_base_url) + url)
                    .post(postData)
                    .build();

            //3.Transport the request and wait for response to process next

            Response response = client.newCall(request).execute();
            String resultData = response.body().string();

            if (resultData.equals("OK")) {

            } else  {
                //post failed
                return "FAILED";


            }


            return resultData;
        } catch (Exception e) {
            Log.d("API_CONNECTION_ERROR", "Couldn't connect to the API");
            return "API_CONNECTION_ERROR";
        }

    }*/


}

我曾经将这个匿名类嵌入到另一个类中并且它有效(它是一个get请求)但问题是它不能以这种方式重用:

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

        URL url = null;

        @Override
        protected void onPreExecute() {

            getActivity().setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                url = new URL (getResources().getString(R.string.backend_base_url) +
                        "api/flrcks/user/id/0/latitude/3000/longitude/300/within/9999999999999999999999999");
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
            // Download complete. Let us update UI
            progressBar.setVisibility(View.GONE);

            if (result == 1) {
                adapter = new MyRecyclerAdapter_Nearby(getActivity(), feedsList);
                mRecyclerView.setAdapter(adapter);
                checkAdapterIsEmpty();
            } else {
                Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
                t.setVisibility(View.VISIBLE);
            }
        }

        private void parseResult(String result) {
            try {
                JSONObject response = new JSONObject(result);

                JSONArray posts = response.getJSONArray("rows");
                feedsList = new ArrayList<>();

                JSONArray members;
                for (int i = 0; i < posts.length(); i++) {
                    memberList = new ArrayList<>();
                    final JSONObject post = posts.optJSONObject(i);
                    members=post.getJSONArray("members");
                    final FeedItem item = new FeedItem();


                //for (int i = 0; i < posts.length(); i++) {
                    //JSONObject post = posts.optJSONObject(i);
                    //FeedItem item = new FeedItem();
                    item.setId(post.optString("id"));
                    item.setTitle(post.optString("name"));
                    item.setDescription(post.optString("description"));
                    item.setPrivacy(post.optString("privacy_mode_description"));
                    item.setInitial_date(post.optString("initial_date"));
                    item.setThumbnail(post.optString("thumbnail"));
                    item.setColor_hex(post.optString("color_hex"));
                    item.setTag(post.optString("tag"));
                    item.setDistance(post.optInt("st_distance"));


                    //item.setThumbnail(post.optString("thumbnail"));

                    for(int k=0; k <members.length();k++)
                    {
                        MemberItem memberItem = new MemberItem();
                        JSONObject member = members.optJSONObject(k);
                        memberItem.setName(member.optString("name"));
                        memberItem.setUsername(member.optString("username"));
                        memberItem.setProfile_pic(member.optString("profile_pic"));
                        memberItem.setIs_moderator(member.optBoolean("is_moderator"));
                        memberItem.setFacebookId(member.optString("facebook_id"));



                        memberList.add(memberItem);
                    }
                    item.setMemberList(memberList);
                    feedsList.add(item);
                }
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

我需要做些什么更改才能将它放在一个孤立的文件中供整个应用程序使用,比如在一个名为OkHTTPRequests.class的文件中

1 个答案:

答案 0 :(得分:0)

创建界面

public interface OnWebResponseListener {
    void onWebResponse(CommonUtilities.services service, String result);
}

创建公开枚举以识别服务。在我的情况下,我创建了一个 CommonUtilities java,我声明了

 public enum services {
        LOGIN
    }

您的公共文件

public class CallAddr extends AsyncTask<String, Void, String> {
    CommonUtilities.services service;
    OnWebResponseListener onWebResponseListener;
    String url;
    FormBody.Builder body;
    Request request;
    OkHttpClient client;
    final static String TAG = "CallAddr";

    public CallAddr(Map<String, String> data, CommonUtilities.services service, OnWebResponseListener onWebResponseListener, String url) {
        this.service = service;
        this.onWebResponseListener = onWebResponseListener;
        this.url = url;
        body = new FormBody.Builder();
        for (String key : data.keySet()) {
            body.add(key, data.get(key));
        }
        client = new OkHttpClient();

    }

    @Override
    protected String doInBackground(String... strings) {
        String result = "";
        request = new Request.Builder().url(url).post(body.build()).build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();

        } catch (Exception e) {
            Log.e(TAG,Log.getStackTraceString(e));
        }
        return result;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (onWebResponseListener != null) {
            onWebResponseListener.onWebResponse(service, s);
        }

    }
}