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;
		}



扫描二维码关注公众号,回复: 4080300 查看本文章

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();  

		}





猜你喜欢

转载自blog.csdn.net/sshzf/article/details/49813897