我正在开发一个Android项目,需要通过URL连接到服务器并发送和获取消息。这些方法位于名为Server Connection的类中。现在我需要在主要活动中调用这些方法,但显然我们不能在主线程上进行网络操作。所以我的问题是当我在服务器连接类中有多个分离方法时,如何使用AsyncTask来执行此操作。代码段如下所示。
服务器连接类:
public class ServerConnection implements Connection{
JSONParser jsonParser = new JSONParser();
ArrayList<Message> messages = new ArrayList<Message>();
JSONObject jsonObject = new JSONObject();
/**
* Constructor
*/
// public ServerConnection() {
// getMessages();
// }
@Override
/**
* gets a set of Messages in form of an ArrayList and pushs it to the Server
*/
public void shareMessage(ArrayList<Message> messages){
this.messages = messages;
jsonObject = jsonParser.parseMessagetoJSON(messages);
//JSONArray share = new JSONArray();
//share.put(jsonObject);
URL url = null;
HttpURLConnection client = null;
try {
url = new URL("URL goes here");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.connect();
Log.d("MSG", "Connection Successful");
client.setRequestProperty("Key","Value");
client.setDoOutput(true);
client.setChunkedStreamingMode(0);
OutputStreamWriter out = new OutputStreamWriter(client.getOutputStream());
.......
.......
}
}
//requests the server for Messages and shares them with the Messanger
public void getMessages(){
try{
URL obj = new URL("URL goes in here");
HttpURLConnection conn = null;
conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
conn.connect();
.......
.......
}
}
}
类似的另一种get方法可以从服务器获取更多数据。现在我需要以某种方式打电话给他们。如何做到这一点使用AsyncTask还是有更简单的方法。
答案 0 :(得分:0)
我强烈建议使用真棒库:Reftrofit 2,OkHttp 3,Gson。它们使REST api非常简单,没有样板代码,你必须使用标准的Android类编写。
请参阅下面的小概念证明如何在您的案例中使用这些库。
首先确保您拥有项目中包含的权限和依赖项:
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
...
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.0-RC1'
compile 'com.squareup.okhttp3:okhttp-urlconnection:3.4.0-RC1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.0-RC1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
接下来使用WS方法
创建适配器public interface RestAdapter {
@POST("/shareMessage/{id}/")
Call<Void> shareMessage(@Path("id") String id, @Body ArrayList<Message> messages);
}
最有趣的事情就在这里。我们创建支持http通信的RestAdapter和在后台调用我们的适配器的ExecutorService函数。在这种情况下,ExecutorService优于AsyncTask,因为可以重复使用。
public class MainActivity extends Activity {
private static final ExecutorService executorService;
private static final RestAdapter restAdapter;
static {
mExecutorService = Executors.newCachedThreadPool();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://foo.com/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
restAdapter = retrofit.create(RestAdapter.class);
}
@Override
protected void onResume() {
super.onResume();
shareMessage();
}
public void shareMessage() {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
restAdapter.shareMessage("1", new ArrayList<Message>()).execute().body();
} catch (IOException e) {
}
}
});
}
}