现在只要我的项目在后端有网络服务。我习惯用这种结构/模式创建我的项目。
项目
- HttpMethods 包
- HttpGetThread
- HttpPostThread
- HttpMultipartPostThread
- HttpGetThread
- 接口(interface)包
- IPostResponse
我在这些 JAVA 文件中编写的代码是,
IPostResponse.java
public interface IPostResponse {
public void getResponse(String response);
}
HttpGetThread.java
public class HttpGetThread extends Thread {
private String url;
private final int HTTP_OK = 200;
private IPostResponse ipostObj;
public HttpGetThread(String url, IPostResponse ipostObj) {
this.url = url;
this.ipostObj = ipostObj;
}
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HTTP_OK) {
InputStream inputStream = httpResponse.getEntity().getContent();
int bufferCount = 0;
StringBuffer buffer = new StringBuffer();
while ((bufferCount = inputStream.read()) != -1) {
buffer.append((char) bufferCount);
}
ipostObj.getResponse(buffer.toString());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在 HttpPost
和 HttpMultipartPost
类中采用相同的方式扩展 Thread
并具有一个构造函数和一个运行方法。
然后,
我实现了一个 Activity 的接口(interface),并将该主要 Activity 扩展到所有其他 Activity ,并通过创建带有参数的 Http 类对象并调用 obj.start();
我仍然相信:我缺少很多东西或者这个结构很差。
我需要知道,Android 应用程序要在几乎所有 Activity 中实现 Web 服务调用并具有代码重用性我应该遵循哪种模式/结构?
我刚刚看到 Facebook 如何进行 Web 服务调用,例如登录/注销它有登录和注销监听器。
是否有任何博客/文章/答案对此进行了详细记录?请问有哪位用户可以分享一下他/她的优秀经验和解决方案吗?
我更感兴趣的是“我的类和接口(interface)应该是什么样子,它应该有什么样的方法?”
最佳答案
第一个也是大多数建议是你为什么不使用 Painless Threading即 AsyncTask
现在第二件事是创建一个与下面相同的可重用代码,您可以使用 Request 参数创建尽可能多的方法。
public class JSONUtil {
private static JSONUtil inst;
private JSONUtil() {
}
public static JSONUtil getInstance() {
if (inst == null)
inst = new JSONUtil();
return inst;
}
/**
* Request JSON based web service to get response
*
* @param url
* - base URL
* @param request
* - JSON request
* @return response
* @throws ClientProtocolException
* @throws IOException
* @throws IllegalStateException
* @throws JSONException
*/
public HttpResponse request(String url, JSONObject request)
throws ClientProtocolException, IOException, IllegalStateException,
JSONException {
synchronized (inst) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(request.toString(), "utf-8"));
HttpResponse response = client.execute(post);
return response;
}
}
public HttpResponse request(String url)
throws ClientProtocolException, IOException, IllegalStateException,
JSONException {
synchronized (inst) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.addHeader("Cache-Control", "no-cache");
HttpResponse response = client.execute(post);
return response;
}
}
}
关于java - android/java在项目中组织http web服务调用的结构/模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13292186/