2016-09-15 65 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