android从主线程上的静态方法+网络返回JSONObject

时间:2017-05-17 16:03:49

标签: java android http android-asynctask

我有这个方法,它在主线程上提供网络。我想使用asynctask在一个单独的线程上进行这个api调用。

但是,业务逻辑禁止我使用非静态方法。代码是:

public static JSONObject acceptOrder(String orderId,Integer loadsToAccept)抛出IOException {

    BufferedReader reader = null;
    JSONObject resultOrder = null;

    AsyncTask asyncTask = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
            return null;
        }
    };
    HttpURLConnection conn = (HttpURLConnection) new URL(GlobalConfig.getInstance().GetGoVulcanConfig().getUrl() + "/api/Order/ProcessAcceptedOrder?acceptedLoads=" + loadsToAccept + "&haulerId=" + GlobalConfig.getInstance().GetGoVulcanConfig().getHaulerId() + "&orderId=" + orderId).openConnection();
    conn.setDoOutput(true);
    //conn.setFixedLengthStreamingMode(jsonString.length());
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept","application/json");
    InputStream inputStream = conn.getInputStream();
    StringBuffer buffer = new StringBuffer();
    if (inputStream == null) {
        // Nothing to do.
        return null;
    }
    reader = new BufferedReader(new InputStreamReader(inputStream));
    String inputLine;
    while ((inputLine = reader.readLine()) != null)
        buffer.append(inputLine);
    if (buffer.length() == 0) {
        // Stream was empty. No point in parsing.
        return null;
    }
    try {
        resultOrder = new JSONObject(buffer.toString());
    }catch (JSONException ex){
        Log.d(ex.getMessage(), "acceptOrder: ");
    }
    conn.disconnect();
    reader.close();
    return resultOrder;
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是我要求POST或GET的表格,我希望可以帮到你

1)我的班级有所有要求

jquery-1.11.1.min.js

2)这是界面

public class RequestManager {

           public static class requestPostExample extends AsyncTask<String, Void, String>{

               Context context;
               int exampleId;
               String exampleData;
               //interface to get the response in the activity
               Public AsynkTaskRespone response = null;

               public requestPostExample(Context context, int exampleID, String exampleData){
                    this.context = context;
                    this.exampleId = exampleID;
                    this.exampleData = exampleData;
                 }

               @Override
               protected String doInBackground(String... params) {
                   try {
                       String urlString = "yourUrl";
                       URL url = new URL(urlString);
                       //the variables and data you want to send by POST
                       String postData = "exampleID="+exampleID+"&exampleData="+exampleData;
                       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                       connection.setDoOutput(true);
                       connection.setRequestMethod("POST");

                       OutputStream os = connection.getOutputStream();
                       os.write(postData.getBytes());

                       StringBuilder responseSB = new StringBuilder();

                       int result = connection.getResponseCode();
                       BufferedReader br;

                       // 401 - 422 - 403  - 500
                      if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500){
                          br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                      }else {
                           br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                      }

                      while ( (JSON_STRING = br.readLine()) != null)
                      responseSB.append(JSON_STRING+ "\n");

                      // Close streams
                      br.close();

                      return responseSB.toString().trim();

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

           @Override
            protected void onPostExecute(String result) {
                 Log.d("Result:", result);
                 //send the result to interface;    
                 response.resultPostExample(result);
            }

}

3)现在进入活动

public interface AsynkTaskRespone {

   void resultPostExample(String result);

}
相关问题