MKJ*_*ekh 8 java android design-patterns
现在,只要我的项目在后端有一个Web服务.我习惯用这种结构/模式创建我的项目.
项目
我在这些JAVA文件中编写的代码是,
IPostResponse.java
public interface IPostResponse {
public void getResponse(String response);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过扩展和拥有一个构造函数和一个run方法,在类HttpPost和HttpMultipartPost类中的方式相同Thread.
然后,
我实现了一个活动的接口,并将该主活动扩展到所有其他活动,并通过使用参数和调用创建Http类的对象来获取响应和调用 obj.start();
我仍然相信:我缺少很多东西,或者这种结构很差.
我需要知道,对于Android应用程序来说,在大多数活动中实现Web服务调用,并且具有代码可重用性,我应该遵循哪种模式/结构?
我刚刚看到Facebook如何进行Web服务调用,例如登录/注销它有登录和注销侦听器.
是否有任何博客/文章/答案都有相同的文件记录?请问,任何用户都能分享他/她的优秀经验和解决方案吗?
我更感兴趣的是" 我的类和界面应该怎样,它应该采用哪种方法? "
第一个也是大多数建议是为什么你不使用无痛线程,即AsyncTask
现在第二件事创建一个可重用的代码,如下所示,您可以创建尽可能多的带有请求参数的方法。
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1449 次 |
| 最近记录: |