网络访问框架XUtils

首先,网络访问方式会有集中,get,post,delete,put,这几种方式
将要访问的url地址放入其中,同时,在HttpResult中,还应该写入返回的信息和返回的结果等,以便调用
代码如下:
package com.android.hht.superapp.net;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.hht.superapp.util.LogUtils;
import com.honghe.common.permission.SecuritySettings;

/**
 * 使用Http的+Oauth的方式请求云端API
 * 
 * @author Jinfu.pi
 * @Created May 27, 2015 9:09:40 AM
 */
public class HttpRequest {

private static final String USERNAME_CREDENTIALS = "app";
private static final String PASSWORD_CREDENTIALS = "910910app";

private static final String AUTH_SCOPE = "edu.honghe-tech.com";

/**
 * post方式获取网络数据
 * 
 * @param params
 * @param uri
 * @return
 * @author Jinfu.pi
 * @Created May 27, 2015 9:09:51 AM
 */
public static JSONObject post(Map<String, String[]> params, String uri) {

DefaultHttpClient client = null;
JSONObject object = null;

List<NameValuePair> pair = getPostParams(params);
try {
client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParams, 10000); // 设置请求超时
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(USERNAME_CREDENTIALS, PASSWORD_CREDENTIALS);
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(new AuthScope(AUTH_SCOPE, 80), creds);
client.setCredentialsProvider(basicCredentialsProvider);
HttpPost post = new HttpPost(API_URL + uri);
post.setEntity(new UrlEncodedFormEntity(pair, "UTF-8"));
LogUtils.d("请求的参数 == " + post.getURI());
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) { // 判断请求的返回码
String result = EntityUtils.toString(response.getEntity());
LogUtils.d("HttpResquest ==   " + result);
object = new JSONObject(result);
}
} catch (Exception e) {
System.err.println("java.net.SocketTimeoutException ======== " + e.getMessage());
}
return object;
}

/**
 * put方式获取网络数据
 * 
 * @param params
 * @param uri
 * @return
 * @author Jinfu.pi
 * @Created Jun 8, 2015 10:28:12 AM
 */
public static JSONObject put(Map<String, String[]> params, String uri) {
DefaultHttpClient client = null;
JSONObject object = null;
List<NameValuePair> pair = getPostParams(params);
try {
client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParams, 10000); // 设置请求超时
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(USERNAME_CREDENTIALS, PASSWORD_CREDENTIALS);
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(new AuthScope(AUTH_SCOPE, 80), creds);
client.setCredentialsProvider(basicCredentialsProvider);
HttpPut put = new HttpPut(API_URL + uri);
put.setEntity(new UrlEncodedFormEntity(pair, "UTF-8"));
LogUtils.d("请求的参数 == " + put.getURI());
HttpResponse response = client.execute(put);
if (response.getStatusLine().getStatusCode() == 200) { // 判断请求的返回码
String result = EntityUtils.toString(response.getEntity());
object = new JSONObject(result);
}
} catch (Exception e) {
System.err.println("java.net.SocketTimeoutException ======== " + e.getMessage());
}
return object;
}

/**
 * delete方式获取网络数据
 * 
 * @param params
 * @param uri
 * @return
 * @author Jinfu.pi
 * @Created Jun 8, 2015 10:27:51 AM
 */
public static JSONObject delete(Map<String, String[]> params, String uri) {
DefaultHttpClient client = null;
JSONObject object = null;
List<NameValuePair> pair = getPostParams(params);
try {
client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParams, 10000); // 设置请求超时
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(USERNAME_CREDENTIALS, PASSWORD_CREDENTIALS);
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(new AuthScope(AUTH_SCOPE, 80), creds);
client.setCredentialsProvider(basicCredentialsProvider);
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(API_URL + uri);
// 设置HttpDelete的请求参数
httpDelete.setEntity(new UrlEncodedFormEntity(pair, "UTF-8"));
HttpResponse response = client.execute(httpDelete);
if (response.getStatusLine().getStatusCode() == 200) { // 判断请求的返回码
String result = EntityUtils.toString(response.getEntity());
LogUtils.d("删除文件夹返回的全部数据 == " + result);
object = new JSONObject(result);
}
} catch (Exception e) {
System.err.println("java.net.SocketTimeoutException ======== " + e.getMessage());
}
return object;
}

/**
 * get方式获取网络数据
 * 
 * @param params
 * @param uri
 * @return
 * @author Jinfu.pi
 * @Created May 27, 2015 9:09:55 AM
 */
public static JSONObject get(Map<String, String[]> params, String uri) {
List<SecuritySettings.Params> paramses = SecuritySettings.setting(params);
String parameter = initParamters(paramses); // 获取加密后的参数
JSONObject object = null;
try {
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(USERNAME_CREDENTIALS, PASSWORD_CREDENTIALS);
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(new AuthScope(AUTH_SCOPE, 80), creds);
HttpGet get = new HttpGet(API_URL + uri + parameter);
DefaultHttpClient client = new DefaultHttpClient(get.getParams());
client.setCredentialsProvider(basicCredentialsProvider);
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 8000); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParams, 6000); // 设置请求超时
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
String result = null;
if (bufferedEntity != null) {
result = getData(bufferedEntity.getContent());
LogUtils.d("HttpResquest ==   " + result);
}
if (result != null) {
object = new JSONObject(result);
}
}
} catch (Exception e) {
object = null;
LogUtils.e(e);
}
return object;
}

/**
 * 
 * @param params
 * @return
 * @author Jinfu.pi
 * @Created May 27, 2015 9:09:59 AM
 */
private final static List<NameValuePair> getPostParams(Map<String, String[]> params) {
List<NameValuePair> result = new ArrayList<NameValuePair>();
List<SecuritySettings.Params> paramses = SecuritySettings.setting(params);
for (SecuritySettings.Params p : paramses) {
LogUtils.d("参数 == " + p.getKey() + " " + p.getValue());
result.add(new BasicNameValuePair(p.getKey(), p.getValue()));
}
return result;
}

/**
 * @TODO 签名参数字符串
 * @param paramses
 * @return
 * @author Jinfu.pi
 * @Created May 27, 2015 9:10:15 AM
 */
private static String initParamters(List<SecuritySettings.Params> paramses) {
String parameter = "";
int temp = 1;
for (SecuritySettings.Params p : paramses) {
if (temp == 1) {
parameter += "?" + p.getKey() + "=" + p.getValue();
} else {
parameter += "&" + p.getKey() + "=" + p.getValue();
}
temp++;
}
return parameter;
}

/**
 * 获取数据,使用缓存、解决内存溢出
 * 
 * @param inputStream
 * @return
 * @throws Exception
 * @author Jinfu.pi
 * @Created May 27, 2015 9:10:28 AM
 */
private static String getData(InputStream inputStream) throws Exception {

String data = null;
// 内存缓冲区
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[8 * 1024];// 每次读一K
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
byte[] bytes = outputStream.toByteArray();
data = new String(bytes);
// data = new String(bytes, "UTF-8");
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
return data;
}
return data;
}

/**
 * 判断请求是否成功
 * 
 * @MethodName: returnResult
 * @Description:
 * @param object
 * @return
 * @return boolean
 *
 */
public static boolean returnResult(JSONObject object) {
boolean resultState = false;
LogUtils.d("返回的数据 == " + object);
if (object != null) {
try {
resultState = (Boolean) object.get("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
LogUtils.d("数据请求是否成功  ==  " + resultState);
return resultState;
}

/**
 * 获取请求完成后返回的信息
 * 
 * @param object
 * @return
 */
public static String returnMessage(JSONObject object) {
String returnMessage = "";
if (object != null) {
try {
Object obj = object.opt("message");
returnMessage = obj.toString();
return returnMessage;
} catch (Exception e) {
e.printStackTrace();
}
}
return returnMessage;
}

}


接下来,就该写接口了,接口的编写,同时也需要写一写公共的方法
因为返回的数据有很多种,所以,写入的公共方法也会分为不同的类型
代码如下
/**
 * 有关网络操作的相关的接口
 *
 * @author Jinfu.pi
 * @Created May 21, 2015 6:11:09 PM
 */
public class HttpDao {

 private static List<FileInfo> fileInfoList = null;
 private static List<FileInfo> folderInfoList = null;

 /**
  * get方式提交数据
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created May 28, 2015 3:02:47 PM
  */
 public static boolean getResult(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  boolean returnValue = false;
  object = HttpRequest.get(requestParams, apiUrl);
  if (object != null) {
   returnValue = (Boolean) HttpRequest.returnResult(object);
   LogUtils.d("返回的数据信息 == " + HttpRequest.returnMessage(object));
  }
  return returnValue;
 }

 /**
  * Post方式提交数据
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created Jun 2, 2015 3:33:48 PM
  */
 public static boolean postResult(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  boolean returnValue = false;
  object = HttpRequest.post(requestParams, apiUrl);
  if (object != null) {
   returnValue = (Boolean) HttpRequest.returnResult(object);
   LogUtils.d("返回的数据信息 == " + HttpRequest.returnMessage(object));
  }
  return returnValue;
 }

 /**
  * put方式提交数据
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created Jun 2, 2015 3:34:05 PM
  */
 public static boolean putResult(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  boolean returnValue = false;
  object = HttpRequest.put(requestParams, apiUrl);
  if (object != null) {
   returnValue = (Boolean) HttpRequest.returnResult(object);
   LogUtils.d("返回的数据信息 == " + HttpRequest.returnMessage(object));
  }
  return returnValue;
 }

 /**
  * delete方式提交数据
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created Jun 2, 2015 3:34:20 PM
  */
 public static boolean deleteResult(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  boolean returnValue = false;
  object = HttpRequest.delete(requestParams, apiUrl);
  if (object != null) {
   returnValue = (Boolean) HttpRequest.returnResult(object);
   LogUtils.d("返回的数据信息 == " + HttpRequest.returnMessage(object));
  }
  return returnValue;
 }

 /**
  * 返回数据data为JSONObject时候的解析
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created May 27, 2015 10:33:16 AM
  */
 public static JSONObject getData2JSONObject(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  JSONObject data = null;
  object = HttpRequest.get(requestParams, apiUrl);
  if (object != null) {
   boolean returnValue = (Boolean) HttpRequest.returnResult(object);
   if (returnValue) {
    data = (JSONObject) object.get("data");
    return data;
   }
  }
  return data;
 }

 /**
  * 返回数据data为JSONArray时候的解析
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created May 27, 2015 10:33:20 AM
  */
 public static JSONArray getData2JSONArray(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  JSONArray data = null;
  object = HttpRequest.get(requestParams, apiUrl);
  if (object != null) {
   boolean returnValue = (Boolean) HttpRequest.returnResult(object);
   if (returnValue) {
    data = (JSONArray) object.get("data");
    return data;
   }
  }
  return data;
 }

 /**
  * 返回的Data中仅有字符串时候的解析
  *
  * @param apiUrl
  * @param requestParams
  * @return
  * @throws JSONException
  * @author Jinfu.pi
  * @Created Jun 5, 2015 5:15:26 PM
  */
 private static String getData2String(String apiUrl, Map<String, String[]> requestParams) throws JSONException {
  JSONObject object = null;
  String data = null;
  object = HttpRequest.get(requestParams, apiUrl);
  if (object != null) {
   boolean returnValue = (Boolean) HttpRequest.returnResult(object);
   if (returnValue) {
    data = (String) object.get("data");
    return data;
   }
  }
  return data;
 }
}

然后,我们写某一个网络访问的时候,根据他的api文档,来判断他返回的数据是什么,是post类型返回的,还是以数组类型返回的,还是以列表形式返回的,还是get方式返回的,将数据封存在一个集合中,
在返回数据的时候,将封存的数据也放进去,这样,就可以将返回的数据解析出来,从而可以取到服务器的数据,像delete,一般都是删除信息的时候,调用这个借口
同时,每调用一个借口,我们就需要传入一个api,这个api对应的每一个接口,拼接上result中提供的总接口,就可以让接口通了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值