这里我就不讲json的基本格式什么的了,首先我使用了4个类用于处理http协议请求服务器的gson格式的数据,本篇只提供客户端的代码,如果需要服务器端代码的可以私密我(让服务器返回json格式的数据就行),在我的资源里有gson的jar包,commons-httpclient-3.1包,在我的资源里都有下载
RequestData 处理请求数据的,用于向服务器发送http请求所带的参数.
HttpRequestUtils 用于封装http协议的请求,不懂的可以查查http协议相关的知识.
RequestResult 请求结果类,用于判断所发送的请求是否执行成功,或网络出现异常.
JsonRequestUtils Json请求帮助类,用于解析.
public class RequestData {
public RequestData() {
}
/**
* 获取停车场
* @param 经度
* @param 纬度
* @return 结果类型
* @throws AppException
*/
public static RequestResult<List<Carpark>> fetchCarparks(double x, double y)
throws AppException {
//这里的Carpark是自己写的类,你可以自定义
List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用android自带的NameValuePaid类来实现参数的传递
params.add(new BasicNameValuePair("x", String.valueOf(x)));
params.add(new BasicNameValuePair("y", String.valueOf(y)));
//http://133.44.33.55/igfdf/gd?jingdu=x&weidu=y
// 使用BasicNameValuePair将参数格式改变成如gd?jingdu=x&weidu=y的形式
TypeToken<RequestResult<List<Carpark>>> typeToken = new TypeToken<RequestResult<List<Carpark>>>() {
};//使用TypeToken定义RequestResult<List<Carpark>>类型,方便后面解析json对象
RequestResult<List<Carpark>> r = JsonRequestUtils
.<List<Carpark>> request("127.0.0.1:8080/aaa/jjj", params, typeToken);//第一个参数传入服务器请求的地址
return r;
}
}
/**
* 网络请求帮助类
* @author Bert guo
*/
public class HttpRequestUtils {
private static final String CHARSET = HTTP.UTF_8; // 设置网络传输编码格式为utf-8
private static final int REQUEST_TIMEOUT = 10 * 1000;// 设置请求超时5秒钟
private static final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间5秒钟
static Header[] headers; // 头文件数组
static {
init(); // 判断版本格式,如果版本>2.3,就用相应的程序进行处理,以便不影响访问网络
}
/**
* 使用post方式进行提交
*
* @param url
* @param formparams
* , 表中的每个字段
* @return 服务器返回的一段字符串,例如[{
* "name":"Mic","age":69},{"name":"Nic","age":69}]
* @throws AppException
*/
public static String post(String url, List<NameValuePair> formparams)
throws AppException {
if (formparams == null) { // 如果字段为空
formparams = new ArrayList<NameValuePair>(); // 实例化一个新的字段集合
} // end of formparams == null
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(formparams, CHARSET); // 设置路径表单实体的编码
HttpPost request = new HttpPost(url); // 创建Post请求
request.setEntity(entity); // 在请求中设置实体类
if (headers != null) {
String cookieValue = "";
for (int i = 0; i < headers.length; i++) {
Header h = headers[i];
cookieValue += ";" + h.getValue(); // 设置头文件
}
request.setHeader("Cookie", cookieValue); // 设置请求的头文件
}
HttpClient client = new DefaultHttpClient(); // 创建一个Http服务对象
// 设置 连接超时时间
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
// 设置 读数据超时时间
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
// 设置 字符集
// client.getParams().setContentCharset(UTF_8);
HttpResponse response = client.execute(request); // 获得Http中响应的对象
headers = response.getHeaders("Set-Cookie"); // 通过响应得到头文件
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) { // 如果无法响应,就抛出异常
throw AppException.http(statusCode);
}
HttpEntity resEntity = response.getEntity(); // 通过响应获取到对应的Http实体
return (resEntity == null) ? null : EntityUtils.toString(resEntity,
CHARSET); // 通过字符串返回对应实体
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw AppException.unsupportedencoding(e);
} catch (ClientProtocolException e) {
e.printStackTrace();
throw AppException.clientprotocol(e);
} catch (ConnectTimeoutException e) {
e.printStackTrace();
throw AppException.connecttimeout(e);
} catch (IOException e) {
e.printStackTrace();
throw AppException.io(e);
}
}
//图片的上传
public static String simpleUri(String urlString, Map<String, Object> params, String imgUrl) {
String result = "";
String end = "rn";
String MULTIPART_FORM_DATA = "multipart/form-data"; // 是我定义的上传URL
String BOUNDARY = "---------7d4a6d158c9"; // 数据分隔线
if (!urlString.equals("")) {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false);// 不使用Cache
conn.setConnectTimeout(6000);// 6秒钟连接超时
conn.setReadTimeout(6000);// 6秒钟读数据超时
conn.setRequestMethod("POST");
// 构造head
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
+ "; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
// 上传的表单参数部分,格式请参考文章
for (Map.Entry<String, Object> entry : params.entrySet()) {// 构建表单字段内容
sb.append("--");
sb.append(BOUNDARY);
sb.append("rn");
sb.append("Content-Disposition: form-data; name=""
+ entry.getKey() + ""rnrn");
sb.append(entry.getValue());
sb.append("rn");
}
sb.append("--");
sb.append(BOUNDARY);
sb.append("rn");
// 上传图片部分
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
dos.write(sb.toString().getBytes());
if (!"".equals(imgUrl) && imgUrl != null) {
dos.writeBytes("Content-Disposition: form-data; name=""
+ "uploadFile" + ""; filename="" + "carpark.jpg" + """ + "rn"
+ "Content-Type: image/jpegrnrn");
FileInputStream fis = new FileInputStream(imgUrl);
byte[] buffer = new byte[1024]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
dos.writeBytes(end);
fis.close();
}
dos.writeBytes("--" + BOUNDARY + "--rn");
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
result = br.readLine();
conn.disconnect();
br.close();
isr.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
result = "{"ret":"898"}";
}
}
return result;
}
// 判断版本格式,如果版本 > 2.3,就是用相应的程序进行处理,以便影响访问网络
private static void init() {
String strVer = android.os.Build.VERSION.RELEASE; // 获得当前系统版本
strVer = strVer.substring(0, 3).trim(); // 截取前3个字符 2.3.3转换成2.3
float fv = Float.valueOf(strVer);
if (fv > 2.3) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
.build());
}
}
}
public class RequestResult<T> {
public static int Success = 1; // 成功
public static int UnKnow = 0; // 未知
public static int Faild = -1; // 失败
public int resultCode; // 状态码 [1:系统成功处理;负数表示系统没有成功处理]
public String desc; //
public T data; // 业务数据,状态码为1时,该数据才有效
public boolean IsSuccess() {
return resultCode == Success;
}
}
public class JsonRequestUtils {
static Gson gson = null; // 声明gson对象
static JsonParser jp = new JsonParser(); // Json解析器
static {
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // 创建gson对象,并设置日期格式
}
public JsonRequestUtils() {
}
/**
* json解析请求
*
* @param serviceName
* :对应Action
* @param remoteMethod
* :请求的方法
* @param params
* :对应表中的字段
* @param typeToken
* :请求的是哪个实体,如Carpark
* @return
* @throws AppException
*/
public static <T> RequestResult<T> request(String path,
List<NameValuePair> params, TypeToken typeToken)
throws AppException {
// AppException是自己定义的异常,你们可以不抛
String json = HttpRequestUtils.post(path, params); // 获得json字符串
Type listType = typeToken.getType(); // 获得类型
RequestResult<T> obj = gson.fromJson(json, listType); // 解析json对象,转换成Carpark对象.
return obj;
}
}
下一篇具体讲讲http协议吧,这个有不懂的可以加我QQ问我,468903507.看过本博客的朋友希望顶顶,小弟才有动力去开放更多的代码.