{aa1aa} 通过 httppost 交互数据:服务端进行数据交互的时候,通常会通过代码进行 http 跨请求,通常使用 post 或 get 方式。在 post 方式的时候,我们可以使用 HttpClient 也可以自己实现方法:
- public static String sendPost(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new 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", "text/html");
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- out = new PrintWriter(conn.getOutputStream());
- out.print(param);
- out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!"+e);
- log.error(e);
- } finally{
- try{
- if(out!=null){
- out.close();
- }
- if(in!=null){
- in.close();
- }
- } catch(IOException ex){
- log.error(ex);
- }
- }
- return result;
- }
比如我们通过代码传递 json 数据:
- String serviceViewTime = HttpUtils.sendPost(dcmsUrl + "dcms/audiencerating/queryServiceViewTime.action",
- "{\"areacode\":" + areacode + ", \"wbegintime\":\"" + wbegintime + "\", \"wendtime\":\"" + wendtime +"\"}");
- log.info("1111serviceViewTime=" + serviceViewTime);
接收端 Action,我们可以通过读取 request 请求体的信息,进而得到数据:
- public void queryServiceViewTime() {
- PrintWriter out = null;
- try {
- out = response.getWriter();
- StringBuffer sb = new StringBuffer();
- InputStream is = request.getInputStream();
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- String str = "";
- while ((str = br.readLine()) != null) {
- sb.append(str);
- }
- MinParam param = new MinParam();
- if(StringUtils.isNotEmpty(sb.toString())) {
- MinParam param1 = JsonUtil.toObjectByJson(sb.toString(), MinParam.class);
- if(null != param1) {
- param = param1;
- }
- } else {
- out.print("");
- return;
- }
- List list = audienceRatingService.getOneDayServiceWatchTime(param.getAreacode() == null ? null: param.getAreacode()+"", param.getWbegintime(),
- param.getWendtime());
- out.print(JsonUtil.toJsonString(list));
- } catch (Exception e) {
- out.print("");
- log.error(e);
- }
- }
也就是从流中读取数据,并转化成我们需要的对象即可。
来源: http://www.2cto.com/kf/201703/613921.html