JAVA接口,json传递

public static String getJsonData(JSONObject jsonParam) {
		StringBuffer sb=new StringBuffer();
		String resultJsonto = new String();
		try {
			// 创建url资源
			URL url = new URL("http://XXXXXXXXX");
			// 建立http连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置允许输出
			conn.setDoOutput(true);
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(100000);
			// 设置允许输入
			conn.setDoInput(true);
			// 设置不用缓存
			conn.setUseCaches(false);
			// 设置传递方式
			conn.setRequestMethod("POST");
			// 设置维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置文件字符集:
			conn.setRequestProperty("Charset", "UTF-8");
			// 转换为字节数组
			//byte[] data = (jsonParam.toString()).getBytes();
			byte[] data = jsonParam.toString().getBytes();
			// 设置文件长度
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			// 设置文件类型:
			conn.setRequestProperty("contentType", "application/json");
			// 开始连接请求
			conn.connect();
			OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
			// 写入请求的字符串
			out.write(jsonParam.toString().getBytes());
			out.flush();
			out.close();
			System.out.println(conn.getResponseCode());
			// 请求返回的状态
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
				System.out.println("连接成功");
				// 请求返回的数据
				InputStream in1 = conn.getInputStream();
				try {
					String readLine=new String();
					BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
					while((readLine=responseReader.readLine())!=null){
						sb.append(readLine).append("\n");
					}
					responseReader.close();
					String json = sb.toString();
					//第一次解码
					String deCode = deCodeBase(json);
					//分割字符串
					String nextIndex =deCode.substring(deCode.indexOf("{"), deCode.length());
					//转换json格式
					JSONObject jsonResult =JSONObject.fromObject(nextIndex); 
					//获取解码message值
					String deCodename = deCodeBase(jsonResult.getString("message"));
					//获取result值
					String resultname = jsonResult.getString("result");
					//返回新JSONObject
					JSONObject resultJson = new JSONObject();
					resultJson.put("message", deCodename);
					resultJson.put("result", resultname);
					//实体类对象转换成String类型的JSON字符串
					resultJsonto = resultJson.toString();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			} else {
				System.out.println("连接失败");
				InputStream error = conn.getErrorStream();
				String errorLine=new String();
				BufferedReader errorresponseReader=new BufferedReader(new InputStreamReader(error,"UTF-8"));
				while((errorLine=errorresponseReader.readLine())!=null){
					sb.append(errorLine).append("\n");
				}
				errorresponseReader.close();
				String errorData = sb.toString();
				System.err.println("错误信息:"+errorData);
			}
		} catch (Exception e) {
			System.out.println("error");
			e.printStackTrace();
		}
		return resultJsonto;
	}

  调用接口

public Map<Integer,Object> work(String str1,String str2,String file) throws Exception {
		str1 = "123";						
		str2 = "456";					
		String mima = UUID.randomUUID().toString();
		//密钥加密
		String requestData = enCodeBase(str1);
		//密钥加密
		String sign = DigestUtils.md5DigestAsHex(str2.getBytes());
		//读取文本文件
		String name = readFileContent(file);
		//获取文本文件内参数
		String utf8 = "";
		try {
			utf8 = new String(name.getBytes(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.err.println("utf8:"+utf8);
		//切割字符串,获取参数
		String[] rows = utf8.split("<br>");
		//批量次数
		Integer rowNum = rows.length;
		//获取返回值
		Map<Integer,Object> resultStr = new HashMap<>();
		for (int i = 0;i<rows.length;i++) {
			System.err.println("Stirng:"+rows[i]);
			//Stirng 转为jsonJSONObject
			JSONObject string1 = JSONObject.fromObject(rows[i]);
			//调用接口
			String str=UserController.getJsonData(string1);
			//防止结果到map
			resultStr.put(i, str);
		}
		for(Entry<Integer, Object> entry : resultStr.entrySet()){
			Integer mapKey = entry.getKey()+1;
		    Object mapValue = entry.getValue();
		    System.out.println("批次:"+mapKey+" : 错误信息:"+mapValue);
		}
		return resultStr;
	}

  相关加密,导入文件方法

//base64位的加密状态
	public static String enCodeBase(String str){
		byte[] enCodeBase;
		try {
			enCodeBase = Base64.encodeBase64(str.getBytes("utf-8"));
			String enCode = new String(enCodeBase,"UTF-8");
			return enCode;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "出现异常";
		}
	}
	//base64位的解密
	public static String deCodeBase(String str){
		byte[] deCodeBase64;
		try {
			deCodeBase64 = Base64.decodeBase64(str.getBytes("UTF-8"));
			String deCode = new String(deCodeBase64,"UTF-8");
			return deCode;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return  "出现异常";
		}
	}
	//获取文本文件
	public static String readFileContent(String fileName) {
	    File file = new File(fileName);
	    BufferedReader reader = null;
	    StringBuffer sbf = new StringBuffer();
	    try {
	        reader = new BufferedReader(new FileReader(file));
	        String tempStr;
	        while ((tempStr = reader.readLine()) != null) {
	            sbf.append(tempStr);
	        }
	        reader.close();
	        return sbf.toString();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (reader != null) {
	            try {
	                reader.close();
	            } catch (IOException e1) {
	                e1.printStackTrace();
	            }
	        }
	    }
	    return sbf.toString();
	}

  

猜你喜欢

转载自www.cnblogs.com/zhang20190701/p/12022738.html
今日推荐