刚刚结束一个项目,做了俩次,第一个版本是根据之前一个类似的项目的代码修改成功的,它使用HttpClient进行Http请求。
<span style="font-family:Courier New;">public class MRequest
{
private static final int NTHREADS = 10;
private Executor executor;//Ï̳߳Ø
private static MRequest instance;
public synchronized static MRequest getInstance()
{
if (instance == null)
{
instance = new MRequest();
}
return instance;
}
public void doPost(final String url, final List<NameValuePair> params,
final int reqType, final String appKey, final MCallback oc)
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
HttpResponse response = null;
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost(url);
if (null != appKey)
{
hp.addHeader("app_key", appKey);
}
if (null != params)
{
hp.setEntity(new UrlEncodedFormEntity(params));
}
response = hc.execute(hp);
if (response.getStatusLine().getStatusCode() == 200)
{
String result = EntityUtils.toString(response
.getEntity());
//TODO:代码处理逻辑
}
else
{
//TODO:代码处理逻辑
}
}
catch (Exception e)
{
//TODO:代码处理逻辑
}
}
});
}
public void doGet(final String url, final int reqType, final MCallback oc,
final String appKey, final boolean isLoadMore)
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
HttpResponse response = null;
try
{
HttpClient hc = new DefaultHttpClient();
HttpGet hp = new HttpGet(url);
if (null != appKey)
{
hp.addHeader("app_key", appKey);
}
response = hc.execute(hp);
if (response.getStatusLine().getStatusCode() == 200)
{
String result = EntityUtils.toString(response
.getEntity());
//TODO:代码处理逻辑
}
else
{
//TODO:代码处理逻辑
}
}
catch (Exception e)
{
//TODO:代码处理逻辑
}
}
});
}
public void doPostJson(final String url, final String json,
final int reqType, final MCallback oc, final String appKey)
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
try
{
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
if (null != appKey)
{
conn.setRequestProperty("app_key",
ConfigApp.getAppKey());
}
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
LogUtil.d("doPostJson() url=" + url + "\n" + "code="
+ conn.getResponseCode());
if (!(conn.getResponseCode() == HttpURLConnection.HTTP_OK || conn
.getResponseCode() == HttpURLConnection.HTTP_CREATED))
{
//TODO:代码处理逻辑
return;
}
BufferedReader br = new BufferedReader(
new InputStreamReader((conn.getInputStream())));
String result = null;
String output = null;
while ((output = br.readLine()) != null)
{
result = output;
}
conn.disconnect();
LogUtil.d("doPostJson()type=" + reqType + " url=" + url
+ "\n" + "result=" + result);
</span><pre name="code" class="java"><span style="font-family:Courier New;"> //TODO:代码处理逻辑</span>
} catch (Exception e) { //TODO:代码处理逻辑 } } }); }}
我重构代码的时候,觉得这个处理过程太麻烦了,所以就查了一下可以使用开源框架Volley来进行http请求,于是就使用了Volley的处理方式,代码的确得到了简化:
<span style="font-family:Courier New;">public class HTTPRequest {
private static RequestQueue mRequestQueue;
private static HTTPRequest instance;
public synchronized static HTTPRequest getInstance(Context context){
if (instance==null){
instance = new HTTPRequest();
mRequestQueue = Volley.newRequestQueue(context);
}
return instance;
}
public void doGet(final MCallback mc, String url, final int type){
StringRequest getRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
HTTPResponseParse.parseResult(mc,response,type);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
MainLogic.getInstance().setNetOk(true);
mc.mCallback(MCallback.RSPTYPE_FAIL,M_HTTP.NETWORK_CANT_BE_USED,0,null);
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("app_key",MGLOBAL.APP_KEY);
return headers;
}
};
mRequestQueue.add(getRequest);
}
public void doPost(final MCallback mc, String url, final int type){
StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
HTTPResponseParse.parseResult(mc,response,type);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
MainLogic.getInstance().setNetOk(true);
mc.mCallback(MCallback.RSPTYPE_FAIL,M_HTTP.NETWORK_CANT_BE_USED,0,null);
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("app_key",MGLOBAL.APP_KEY);
return headers;
}
};
mRequestQueue.add(postRequest);
}
}</span>