注:網(wǎng)絡請求等耗時代碼不要在主線程(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方式提交數(shù)據(jù)
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);? ? ? ? ? ? ? ? ? ? ? ? //打開輸入流,以便從服務器獲取數(shù)據(jù)
httpURLConnection.setDoOutput(true);? ? ? ? ? ? ? ? ? ? ? //打開輸出流,以便向服務器提交數(shù)據(jù)
httpURLConnection.setRequestMethod("POST");? ? ? //設置以Post方式提交數(shù)據(jù)
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();? ? ? ? ? ? ? ? ? ? ? ? ? ? //獲得輸出流,向服務器寫入數(shù)據(jù)
//outputStream.write(data); 普通數(shù)據(jù)
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";// 內(nèi)容類型
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;
}