2016-09-15 61 views
0

我想確定是否有更好的方式我的下面的代碼,發送數據到服務器的方式下面的工作,但可以更好?另一種方式比AsyncTask發送數據到服務器

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... params) { 

     String json = ""; 
     String s_calc=String.valueOf(calc);; 


     try { 
      RequestBody formBody = new FormEncodingBuilder() 
        // .add("tag","login") 
        .add("likes", "9") 
        .add("id", id) 
        .build(); 
      Request request = new Request.Builder() 
        .url("http://justedhak.com/old-files/singleactivity.php") 
        .post(formBody) 
        .build(); 
      Response responses = null; 
      try { 
       responses = client.newCall(request).execute(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      String jsonData = responses.body().string(); 
      JSONObject Jobject = new JSONObject(jsonData); 

      int success = Jobject.getInt("success"); 
      if (success == 1) { 
       // this means that the credentials are correct, so create a login session. 
       JSONArray JAStuff = Jobject.getJSONArray("stuff"); 
       int intStuff = JAStuff.length(); 
       if (intStuff != 0) { 
        for (int i = 0; i < JAStuff.length(); i++) { 
         JSONObject JOStuff = JAStuff.getJSONObject(i); 
         //create a login session. 
        //  session.createLoginSession(name, pass); 
        } 
       } 

      } else { 
       // return an empty string, onPostExecute will validate the returned value. 
       return ""; 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Log.e("MYAPP", "unexpected JSON exception", e); 
     } 

     //this return will be reached if the user logs in successfully. So, onPostExecute will validate this value. 
     return "RegisterActivity success"; 
    } 


    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     // if not empty, this means that the provided credentials were correct. . 
     if (!result.equals("")) { 
      finish(); 
      return; 
     } 
     //otherwise, show a popup. 
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this); 
     alertDialogBuilder.setMessage("Wrong username or password, Try again please."); 
    // alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     //  @Override 
     // public void onClick(DialogInterface arg0, int arg1) { 
      //  alertDialog.dismiss(); 
     // } 
     // }); 
     // alertDialog = alertDialogBuilder.create(); 
     // alertDialog.show(); 
    } 
} 
+2

使用改造http://square.github.io/retrofit/ –

+0

其類似於okttp的權利? @KenWolf – Moudiz

+1

Retrofit使用OKHttp作爲http客戶端 –

回答

2

「更好」是主觀的,但作爲@KenWolf指出的那樣,我相信一般的共識是,Retrofit是去訪問你的服務器API的方式。 Retrofit依賴於OkHttp,並且可以使用各種converters爲您解析JSON(包括Gson和我的首選項Moshi)。它也是compatibleRxJava(和RxAndroid),它可以使世界的差異。

Google的一個替代方案Retrofit應該是Volley,儘管它的抽象程度要低得多。另外,谷歌還沒有生成Retrofit所具有的任何類似的支持庫,並且僅支持用於反序列化的Gson

+0

是不是由Google管理的ProtoBuf? –

+0

你能否提供或顯示一個例子的鏈接 – Moudiz

+1

@ cricket_007在什麼方面? Google確實爲[選擇語言](https://developers.google.com/protocol-buffers/docs/tutorials)維護了協議緩衝區API,但沒有維護與「Retrofit」或「Volley」兼容的任何庫。 Square確實爲'Retrofit'維護了一個ProtoBuf庫。 – Bryan

2

您已經在使用OkHttp。所以,你甚至不需要一個AsyncTask異步GET可以在一個AsyncTask之外使用。如果你明確地使用JSON請求,那麼Retrofit或者Volley就是很好的選擇。

private final OkHttpClient client = new OkHttpClient(); 

    public void run() throws Exception { 
    Request request = new Request.Builder() 
     .url("http://publicobject.com/helloworld.txt") 
     .build(); 

    client.newCall(request).enqueue(new Callback() { 
     @Override public void onFailure(Call call, IOException e) { 
     e.printStackTrace(); 
     } 

     @Override public void onResponse(Call call, Response response) throws IOException { 
     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 

     Headers responseHeaders = response.headers(); 
     for (int i = 0, size = responseHeaders.size(); i < size; i++) { 
      System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); 
     } 

     System.out.println(response.body().string()); 
     } 
    }); 
    } 
+0

我有問題與圖像和緩存相關的抽象我不reaclty,所以用okhttp沒有必要使用asyntask永遠不對? – Moudiz

+0

可能有必要的時候,但我現在想不出任何 –

+2

@Moudiz [你不應該使用帶有'OkHttp'的'AsyncTask'。](http://stackoverflow.com/a/27341320/5115932) – Bryan