标签:host open 设置 edr col 数据交互 win read targe
在进行程序之间数据通信时我们有时候就需要自定义二进制格式,然后通过HTTP进行二进制数据交互。交互的示例代码如下:
public static void main(String[] args) { String result = ""; try { String url = "http://localhost:8080/Demo/SiteApi"; URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/octet-stream"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 发送请求参数 DataOutputStream dos=new DataOutputStream(conn.getOutputStream()); String content="I love china"; dos.write(content.getBytes()); // flush输出流的缓冲 dos.flush(); // 定义BufferedReader输入流来读取URL的响应 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } System.out.println(result);//打印输出结果 } catch (Exception e) { System.out.println("异常," + e.getMessage()); e.printStackTrace(); } }
说一下重点吧:
1.设置Content-Type的值必须为application/octet-stream,可参考http://tool.oschina.net/commons/
2.发送二进制数据必须使用到DataOutputStream
标签:host open 设置 edr col 数据交互 win read targe
原文地址:http://www.cnblogs.com/duanjt/p/7842761.html