`

Java后台方法请求url浏览器打开一个窗口

 
阅读更多

项目中遇到一个这样的需求:在本系统A中组装参数,然后再根据系统B提供的部分uri,组装一个完整的url类似

"http://127.0.0.1:8090/test/index.jsp?userId=123&prjId=51011
通过http协议来访问系统B。当点击系统A中的链接,在浏览器中打开一个tab页展示系统B对应的内容。
就这么一个小小的需求,折腾了一天,不过问题总算解决了!在此记录!
第一反应使用重定向来说实现,但是重定向使用get方式提交,提交的参数长度是有限制的,大概256个字符吧
由于项目中组装的参数可能会超过256,则此种方法不能使用。

于是想到使用HttpClient,可是要使用HttpClient必须添加所依赖的jar,但是又不想添加jar,则此种方式作为

备用方案!

有同事说可以使用HttpUrlConnection,开发中遇到参数传递时,系统B中死活获取不到参数。于是查找原因,初

步确定为servlet在forward的时候,把参数给搞丢了。至今这个问题还没有想出解决方法,如果你有好的解决方

法,还请指点。。。

无奈只好使用HttpClient,实现方法很简单,直接贴代码吧

 

String postURL = "http://127.0.0.1:8090/test/index.jsp";
  HttpClient httpClient = new DefaultHttpClient();
  httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET,"UTF-

8"); 
  HttpPost httpPost = new HttpPost(postURL);
  
        StringEntity reqEntity = new StringEntity(returnUrl(request, response),"UTF-8");
        reqEntity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(reqEntity);
        
        /*List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("USERNAME", "测试"));
        nvps.add(new BasicNameValuePair("USERID", "123"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));*/

        HttpResponse httpResponse = httpClient.execute(httpPost);
        
        StatusLine status= httpResponse.getStatusLine();
        
        if(200 == status.getStatusCode()){
         HttpEntity httpEntity = httpResponse.getEntity();
         if(httpEntity != null){
          String htmlContext = EntityUtils.toString(httpEntity);
           
          response.setContentType("text/html;charset=UTF-8");
          response.setCharacterEncoding("UTF-8");
          response.getWriter().print(htmlContext);
          //采用二进制输出中文乱码
    //response.getOutputStream().print(new String(sbf.toString
().getBytes("ISO-8859-1"),"UTF-8"));
                
         }
         EntityUtils.consume(httpEntity);
        }
        
        httpClient.getConnectionManager().shutdown();



/*String uri = "http://127.0.0.1:8080/test/index.jsp"+"?"+returnUrl(request, response);
        
  response.sendRedirect(uri);*/

 

 

注意:

      response.setContentType("text/html;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().print(htmlContext);

告诉浏览器怎么显示请求返回的数据。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics