java访问其他项目接口

    现在调用其他项目的接口用的比较多的应该是webservice和httpclient这类的吧,我现在做的项目还是比较老的那种,用的还是java自带的包里面  的HttpURLConnection类,HttpURLConnection位于rt.jar下的 java.net下


	public String loadJSONFforISP(String url) {
		StringBuilder json = new StringBuilder(); //返回json数据
		String ISPTimeOut = DictionaryUtils.codeToName("ISP","ISPTimeOut");//设置响应时间
		try {
			URL u = new URL(url);//设置url
			HttpURLConnection yc = (HttpURLConnection) u.openConnection();//设置请求相关参数
			yc.setRequestMethod("GET");
			 yc.setDoOutput(true);
			 yc.setDoInput(true);
			yc.setAllowUserInteraction(false);
			yc.setUseCaches(false);
			yc.setConnectTimeout(Integer.parseInt(ISPTimeOut));
			yc.setRequestProperty("Accept-Charset", "utf-8");
			yc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			yc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			yc.connect();
			BufferedInputStream bis = new BufferedInputStream(yc.getInputStream());
			BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	 return json.toString();
	}

        返回的json用

OSPResponseResult data = new OSPResponseResult();
        data=JSON.deserialize(json, data.getClass());

        用对象接住,记住根据json返回的数据格式来建立接的对象   打比方是这种

{"data":[     {"channel":"CM","username":"000002079                     ","city":"SH                  ","phone":"18611192345    ","agency":"G00000147","office":"YA01  ","rank":"A1","to_be_rank":"  ","status":"A","mon_att_ra":"87.50","eafiller3":"NYI0ACMNNNNBY NYYY Y"}],"success":"true","message":"查找成功"}

        数组里面数据就得用一个list来接  还要记住对象名要跟返回的json数据名一样

上面用的是get方式,下面是post方式

                try {
                        //请求对象参数
						String str = JSON.serialize(req);
						url = getURL(req.getCo(),"Y");
						URL u = new URL(url);//访问路径
						HttpURLConnection yc = (HttpURLConnection) u.openConnection();
						yc.setRequestMethod("POST");
						// yc.setRequestProperty("Content-type", "application/json");
						yc.setDoOutput(true);
						yc.setDoInput(true);
						yc.setUseCaches(false); // 设置是否缓存
						//设置超时
						yc.setConnectTimeout(Integer.parseInt(NBTimeOut));
						yc.setReadTimeout(Integer.parseInt(NBTimeOut));
						OutputStream outputStream = yc.getOutputStream();
						outputStream.write(str.getBytes("UTF-8"));
						outputStream.close();
						BufferedReader in = new BufferedReader(new InputStreamReader(
								yc.getInputStream(), "UTF-8"));
						String inputLine = null;
						while ((inputLine = in.readLine()) != null) {
							json.append(inputLine);
						}
						logger.info("loadJSON  Spare end");
						in.close();
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
					logger.error("loadJSON入参:"+url);
				}
		

		return json.toString();

 

你可能感兴趣的:(java)