`
fred_张浩
  • 浏览: 31067 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

小码农的代码(五)----------web交互之HTTP传输HttpURLConnection

阅读更多
工作中难免会遇到多系统交互的问题,回顾开发过的项目有用过公司内部封装的scoket,也有webService,目前物流系统与上游ERP系统与下游仓储系统对接使用的是http方式的交互,因此先来记录一下http方式交互的代码编写思路与内容,在后续的博文中再来讨论scoket与webservice。
对于http自然就有get与post两种方式,我的理解是get方式更倾向于消息的获取,而post在于信息的交互与修改,在请求中get方式会在url中出现明文的参数,而post方式相对来说就更加安全而且请求没有大小限制。
在本文中使用的是URLConnection来实现http post传输。首先新建一个Url,


URL localURL = new URL("http://localhost:8080/HttpServerDemo/servlet/LoginServlet");HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

然后打开一个url连接,
URLConnection connection = localURL.openConnection();
再者设置相关的http报文头,设置请求方法为POST
httpURLConnection.setDoOutput(true);//使用 URL 连接进行输出
		httpURLConnection.setDoInput(true);//使用 URL 连接进行输入
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
		httpURLConnection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		httpURLConnection.setRequestProperty("Content-Length",
				String.valueOf(parameterData.length()));

最后就是通过流形式将参数内容写入请求体中。
OutputStream outputStream = httpURLConnection.getOutputStream();OutputStreamWriter outputStreamWriter = null;
outputStreamWriter = new OutputStreamWriter(outputStream,"utf-8");
			outputStreamWriter.write("请求参数");			outputStreamWriter.flush();
调用完毕之后记得关闭流同样的,如果需要将服务端的返回信息进行打印,也通过流的方式获取并输出。
InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;inputStream = httpURLConnection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream);
			reader = new BufferedReader(inputStreamReader);

			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}
这里有个注意点就是reader.readLine()需要赋值之后再去判断,否则判断的值与循环体内的tempLine的值不一致导致错误,另外同样需要关闭流接下去就是服务端的代码新建一个servlet,通过request.getInputStream()输入流获取请求内容并打印
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( request.getInputStream(),"utf-8"));
        StringBuffer buffer = new StringBuffer();
        String line = new String();
        while ((line = bufferedReader.readLine()) != null) {
        	buffer.append(line).append("\n");
		}
        System.out.println(buffer.toString());
对于需要输出到客户端的返回报文同样写入输出流通过response输出
 response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain; charset=UTF-8");
       PrintWriter writer = response.getWriter();
        writer.write(buffer.toString());
        response.getWriter().write("It is ok!");
这里有个注意点就是对于输出编码的设置必须在写入流之前对response进行设置才能起到效果最后关闭各个流。
这样,一个简单的http post请求与服务器响应就写完了,总结而言就是将参数信息通过输出流的方式写入到请求中,通过HttpURLConnection方式传递到服务器。服务器对请求内容进行解析并返回到客户端。
而在实际的开发过程中,多数情况是在获得服务器请求报文格式的前提下进行开发,这时就只需要按照报文格式来向服务端发送请求即可,通常报文支持json或者xml格式,下面就对这两种方式写一个简单的测试用例。首先是json格式的只需要将前文中outputStreamWriter.write("请求测试")的内容替换为jsonObject.toString()即可,xml同理。
JSONObject jsonObject = new JSONObject();
		jsonObject.append("username", "fredzhanghao");
		jsonObject.append("blog", "http://675990021.iteye.com/admin");
		jsonObject.append("test", "中文测试");
json格式需要加载json包,具体见pom文件
1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics