本文共 2306 字,大约阅读时间需要 7 分钟。
最近一个项目需要在http传输过程中进行数据加密,则需要通过流来读写http请求的包体内容,结果发现在接收方获取到的流数据是空的,最后发现是因为没有设置请求数据内容类型的缘故,即此行代码:
conn.setRequestProperty("content-type", "text/html");
以下展示整个基于java的http请求的发起和接收
public String httpRequest(String requestUrl, String requestMethod, MaprequestParameters) throws IOException { try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);//需要用到输出流 conn.setDoInput(true);//需要用到输入流 conn.setRequestMethod(requestMethod); conn.setRequestProperty("content-type", "text/html");//设置内容类型 // 使用输出流添加数据至请求体 if (requestParameters.size() != 0) { String json = Context.gson.toJson(requestParameters);//转换为json OutputStream os = conn.getOutputStream();//获取输出流 os.write(json.getBytes());//写入 os.flush(); } conn.connect(); // 读取服务器端返回的内容 InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); StringBuffer buffer = new StringBuffer(); String line; while ((line = br.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (Exception e) { logger.error("http请求异常", e); throw e; }}
public String activate(){ InputStream is = null; try { is = request.getInputStream();//获取输入流 ArrayListarr = new ArrayList (); byte[] buffer = new byte[50];//缓存数组 int len; //读取数据 while ((len=is.read(buffer))!=-1) { for (int i = 0; i < len; i++) { arr.add(buffer[i]); } } byte[] src = new byte[arr.size()]; for (int i = 0; i < src.length; i++) { src[i] = arr.get(i); } String json = new String(src); @SuppressWarnings("unchecked") Map map = Context.gson.fromJson(json, HashMap.class); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) is.close(); } return SUCCESS;}
要对传输的数据进行加密,则只需要在写入和读取的位置对数据进行加密即可
转载地址:http://ovtlf.baihongyu.com/