注:网络请求等耗时代码不要在主线程(UI线程中)
HTTPURLCONNECTION
get方法:
try{
URL url =newURL(URLConfig.PIURL+ Action);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(3000);
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setRequestMethod("GET");//设置以GET方式提交数据
httpURLConnection.setRequestProperty("Cookie",cookie); //可以不设置
httpURLConnection.connect(); // 建立连接
int response = httpURLConnection.getResponseCode();//获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
returndealResponseResult(inptStream);//处理服务器的响应结果
//bm = BitmapFactory.decodeStream( inptStream ); 获取图片
}
}catch(Exception e) {
e.printStackTrace();
return"";
}
post
byte[] data = getRequestData(params, "utf-8").toString().getBytes(); //获得请求体
try {
URL url = new URL(URLConfig.PIURL + URLConfig.ACTION_BUY_TICKET);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
httpURLConnection.setRequestProperty("Cookie", cookie);//设置cookie 可以不设置
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length)); //设置请求体的长度
OutputStream outputStream = httpURLConnection.getOutputStream(); //获得输出流,向服务器写入数据
//outputStream.write(data); 普通数据
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if (response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
return dealResponseResult(inptStream); //处理服务器的响应结果
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
post 图片
String BOUNDARY = UUID.randomUUID().toString();// 边界标识 随机生成
String PREFIX ="--",LINE_END ="\r\n";
String CONTENT_TYPE ="multipart/form-data";// 内容类型
try{
URL url =newURL(URLConfig.PIURL+ URLConfig.ACTION_UPLOAD);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false);// 不允许使用缓存
conn.setRequestMethod("POST");// 请求方式
conn.setRequestProperty("Charset","utf-8");// 设置编码
conn.setRequestProperty("connection","keep-alive");
conn.setRequestProperty("Cookie",cookie);
conn.setRequestProperty("Content-Type",CONTENT_TYPE +";boundary="+ BOUNDARY);
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos =newDataOutputStream(conn.getOutputStream());
StringBuffer sb =newStringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+"photo.jpg"+"\""+ LINE_END);
sb.append("Content-Type: application/octet-stream; charset="+"utf-8"+ LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
if(photo !=null) dos.write(photo,0,photo.length);
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
intres = conn.getResponseCode();
Log.e(TAG,"response code:"+ res);
if(res ==200) {
Log.e(TAG,"request success");
InputStream input = conn.getInputStream();
returndealResponseResult(input);
}else{
Log.e(TAG,"request error");
}
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
return"";
}
处理响应结果
StringdealResponseResult(InputStream inputStream) {
String resultData =null;//存储处理结果
ByteArrayOutputStream byteArrayOutputStream =newByteArrayOutputStream();
byte[] data =new byte[1024];
int len =0;
try{
while((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data,0,len);
}
}catch(IOException e) {
e.printStackTrace();
}
resultData =newString(byteArrayOutputStream.toByteArray());
Log.d(TAG," OK! -- "+ resultData);
returnresultData;
}