1. 程式人生 > >HttpURLConnection往伺服器傳送請求

HttpURLConnection往伺服器傳送請求

HttpURLConnection往伺服器傳送請求

get請求:


private int submitDataByDoGet(Map<String, String> map, String path) throws Exception {
		// TODO Auto-generated method stub
		//將請求引數拼接成url
		StringBuilder sb = new StringBuilder(path);
		sb.append("?");
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue());
			sb.append("&");
		}
		sb.deleteCharAt(sb.length() - 1);//去掉最末尾的&
		String str = sb.toString();
		 URL Url = new URL(str); 
		 HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
		 HttpConn.setRequestMethod("GET");//get請求
		 HttpConn.setConnectTimeout(60000);
		 HttpConn.setReadTimeout(60000);
		 int responseCode = HttpConn.getResponseCode() ;
		 if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {

			//處理請求返回result//result形式:{"result":{"keyword":"xxxxx","description":"sdfa","username":null,"pictur			e":null,"id":41.0,"name":"xxx","updatetime":"2015-11-09 09:52:39","type1":"E7N6R14B03001437","inputtime"			:"2015-11-09 09:40:50","code":"E7N6R14B03001437","the_geom":"POINT (0.0 0.0)"},"success":true,"msg":"登入			成功!"}
			 InputStream inStream = HttpConn.getInputStream();  
			 byte[] data = readInputStream(inStream); 
			 String json = new String(data); 			 
			//用此形式處理返回json
			 JSONArray array = new JSONArray("["+json+"]"); 
			 String result="";
			 for(int i=0 ; i < array.length() ; i++) 
			 {
  				 JSONObject item = array.getJSONObject(i); 
  				 String flag = item.getString("success"); 				 
  				 result = item.getString("result");  				
				 if (flag == "false"){
					 responseCode =2;
					 Message = item.getString("msg");;
				 }else{
					 responseCode =1;
				 }
			 }
			 //處理返回結果中的json包含的子json:{"keyword":"xxxxx","description":"sdfa","username":null,"pictur			e":null,"id":41.0,"name":"xxx","updatetime":"2015-11-09 09:52:39","type1":"E7N6R14B03001437","inputtime"			:"2015-11-09 09:40:50","code":"E7N6R14B03001437","the_geom":"POINT (0.0 0.0)"}
			 if(result!="null"){
				 JSONArray resultInfo = new JSONArray("["+result+"]");
				 for(int i=0 ; i < resultInfo.length() ; i++) 
				 {
					 try{
						 JSONObject item = resultInfo.getJSONObject(i); 
		  				 gpsId = item.getDouble("id");
					 }
					 catch(Exception e){
						 e.printStackTrace();
					 }
	  				 
				 }
			 }
			 
			 return responseCode;
		 }
		 return responseCode;
	}



post請求:


private int submitDataByDoPost(Map<String, String> map, String path) throws Exception {
			// TODO Auto-generated method stub
			StringBuilder sb = new StringBuilder();
			//sb.append("?");
			for (Map.Entry<String, String> entry : map.entrySet()) {
				sb.append(entry.getKey()).append("=").append(entry.getValue());
				sb.append("&");
			}
			sb.deleteCharAt(sb.length() - 1);
			String str = sb.toString();
			 URL Url = new URL(path);//post請求不能在url後面直接帶引數
			 HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
			 HttpConn.setRequestMethod("POST");//post請求
			 HttpConn.setConnectTimeout(60000);
			 HttpConn.setReadTimeout(60000);
			 HttpConn.setDoOutput(true);//請求帶參
			 HttpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");//設定請求Content-Type為:application/x-www-form-urlencoded;charset=UTF-8,這個根據需要設定,可解決伺服器端接收為亂碼

			 HttpConn.setRequestProperty("Content-Length", String.valueOf(str.getBytes().length)); 
			 OutputStream os = HttpConn.getOutputStream();
			 os.write(str.getBytes());  
			 int responseCode = HttpConn.getResponseCode();
			 if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				 InputStream inStream = HttpConn.getInputStream();  
				 byte[] data = readInputStream(inStream); 
				 String json = new String(data); 
				 JSONArray array = new JSONArray("["+json+"]"); 
				 for(int i=0 ; i < array.length() ; i++) 
				 {
	  				 JSONObject item = array.getJSONObject(i); 	  				 
	  				 String flag = item.getString("success");
					 if (flag == "false"){
						 responseCode =2;
					 }else{
						 responseCode =1;
					 }
				 }
				 return responseCode;
			 }else{
				 
			 }
			 return responseCode;
		}



private byte[] readInputStream(InputStream inStream) throws Exception{
			// TODO Auto-generated method stub
			 ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
			 byte[] buffer = new byte[1024];  
			 int len = 0;  
			 while( (len=inStream.read(buffer)) != -1 ){  
			       outStream.write(buffer, 0, len);  
			 }  
			 inStream.close();  
			 return outStream.toByteArray();  

		}