weixin_42393350 2010-11-16 11:29
浏览 563
已采纳

URLConnection传递参数后的问题

现在有需求需要用java的URLConnection发送请求并传递参数,就在网上找了代码来研究。代码如下:

[color=green]import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

/**

  • HTTP请求[qing qiu]代理类
  • @author benl
  • @version 1.0, 2007-7-3
    */
    public class HttpRequestProxy {

    /**

    • 连接[lian jie]超时[chao shi] */ private static int connectTimeOut = 5000;

    /**

    • 读取[du qu]数据[shu ju]超时[chao shi] */ private static int readTimeOut = 10000;

    /**

    • 请求[qing qiu]编码[bian ma] */ private static String requestEncoding = "GBK";

    private static Logger logger = Logger.getLogger(HttpRequestProxy.class);

    /**

    • 发送带参数[can shu]的GET的HTTP请求[qing qiu]
    • @param reqUrl
    • HTTP请求[qing qiu]URL
    • @param parameters
    • 参数[can shu]映射[ying she]表
    • @return HTTP响应[xiang ying]的字符[zi fu]串[zi fu chuan]
      */
      public static String doGet(String reqUrl, Map parameters,
      String recvEncoding) {
      HttpURLConnection url_con = null;
      String responseContent = null;
      try {
      StringBuffer params = new StringBuffer();
      for (Iterator iter = parameters.entrySet().iterator(); iter
      .hasNext();) {
      Entry element = (Entry) iter.next();
      params.append(element.getKey().toString());
      params.append("=");
      params.append(URLEncoder.encode(element.getValue().toString(),
      HttpRequestProxy.requestEncoding));
      params.append("&");
      }

      if (params.length() > 0) {
          params = params.deleteCharAt(params.length() - 1);
      }
      
      URL url = new URL(reqUrl);
      url_con = (HttpURLConnection) url.openConnection();
      url_con.setRequestMethod("GET");
      System.setProperty("sun.net.client.defaultConnectTimeout", String
              .valueOf(HttpRequestProxy.connectTimeOut));// (单位[dan
                                                          // wei]:毫秒)jdk1.4换成这个,连接[lian
                                                          // jie]超时[chao
                                                          // shi]
      System.setProperty("sun.net.client.defaultReadTimeout", String
              .valueOf(HttpRequestProxy.readTimeOut)); // (单位[dan
                                                          // wei]:毫秒)jdk1.4换成这个,读操作超时[chao
                                                          // shi]
      // url_con.setConnectTimeout(5000);//(单位[dan wei]:毫秒)jdk
      // 1.5换成这个,连接[lian jie]超时[chao shi]
      // url_con.setReadTimeout(5000);//(单位[dan wei]:毫秒)jdk
      // 1.5换成这个,读操作超时[chao shi]
      url_con.setDoOutput(true);
      byte[] b = params.toString().getBytes();
      url_con.getOutputStream().write(b, 0, b.length);
      url_con.getOutputStream().flush();
      url_con.getOutputStream().close();
      
      InputStream in = url_con.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(in,
              recvEncoding));
      String tempLine = rd.readLine();
      StringBuffer temp = new StringBuffer();
      String crlf = System.getProperty("line.separator");
      while (tempLine != null) {
          temp.append(tempLine);
          temp.append(crlf);
          tempLine = rd.readLine();
      }
      responseContent = temp.toString();
      rd.close();
      in.close();
      

      } catch (IOException e) {
      logger.error("网络[wang luo]故障[gu zhang]", e);
      } finally {

      if (url_con != null) {
          url_con.disconnect();
      }
      

      }

      return responseContent;
      }

    /**

    • 发送不带参数[can shu]的GET的HTTP请求[qing qiu]
    • @param reqUrl
    • HTTP请求[qing qiu]URL
    • @return HTTP响应[xiang ying]的字符[zi fu]串[zi fu chuan]
      */
      public static String doGet(String reqUrl, String recvEncoding) {
      HttpURLConnection url_con = null;
      String responseContent = null;
      try {
      StringBuffer params = new StringBuffer();
      String queryUrl = reqUrl;
      int paramIndex = reqUrl.indexOf("?");

      if (paramIndex > 0) {
          queryUrl = reqUrl.substring(0, paramIndex);
          String parameters = reqUrl.substring(paramIndex + 1, reqUrl
                  .length());
          String[] paramArray = parameters.split("&");
          for (int i = 0; i < paramArray.length; i++) {
              String string = paramArray[i];
              int index = string.indexOf("=");
      
              if (index > 0) {
                  String parameter = string.substring(0, index);
                  String value = string.substring(index + 1, string
                          .length());
                  params.append(parameter);
                  params.append("=");
                  params.append(URLEncoder.encode(value,
                          HttpRequestProxy.requestEncoding));
                  params.append("&");
              }
          }
      
          params = params.deleteCharAt(params.length() - 1);
      }
      
      URL url = new URL(queryUrl);
      url_con = (HttpURLConnection) url.openConnection();
      url_con.setRequestMethod("GET");
      System.setProperty("sun.net.client.defaultConnectTimeout", String
              .valueOf(HttpRequestProxy.connectTimeOut));// (单位[dan
                                                          // wei]:毫秒)jdk1.4换成这个,连接[lian
                                                          // jie]超时[chao
                                                          // shi]
      System.setProperty("sun.net.client.defaultReadTimeout", String
              .valueOf(HttpRequestProxy.readTimeOut)); // (单位[dan
                                                          // wei]:毫秒)jdk1.4换成这个,读操作超时[chao
                                                          // shi]
      // url_con.setConnectTimeout(5000);//(单位[dan wei]:毫秒)jdk
      // 1.5换成这个,连接[lian jie]超时[chao shi]
      // url_con.setReadTimeout(5000);//(单位[dan wei]:毫秒)jdk
      // 1.5换成这个,读操作超时[chao shi]
      url_con.setDoOutput(true);
      byte[] b = params.toString().getBytes();
      url_con.getOutputStream().write(b, 0, b.length);
      url_con.getOutputStream().flush();
      url_con.getOutputStream().close();
      InputStream in = url_con.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(in,
              recvEncoding));
      String tempLine = rd.readLine();
      StringBuffer temp = new StringBuffer();
      String crlf = System.getProperty("line.separator");
      while (tempLine != null) {
          temp.append(tempLine);
          temp.append(crlf);
          tempLine = rd.readLine();
      }
      responseContent = temp.toString();
      rd.close();
      in.close();
      

      } catch (IOException e) {
      logger.error("网络[wang luo]故障[gu zhang]", e);
      } finally {

      if (url_con != null) {
          url_con.disconnect();
      }
      

      }

      return responseContent;
      }

    /**

    • 发送带参数[can shu]的POST的HTTP请求[qing qiu]
    • @param reqUrl
    • HTTP请求[qing qiu]URL
    • @param parameters
    • 参数[can shu]映射[ying she]表
    • @return HTTP响应[xiang ying]的字符[zi fu]串[zi fu chuan]
      */
      public static String doPost(String reqUrl, Map parameters,
      String recvEncoding) {
      HttpURLConnection url_con = null;
      String responseContent = null;
      try {
      StringBuffer params = new StringBuffer();
      for (Iterator iter = parameters.entrySet().iterator(); iter
      .hasNext();) {
      Entry element = (Entry) iter.next();
      params.append(element.getKey().toString());
      params.append("=");
      params.append(URLEncoder.encode(element.getValue().toString(),
      HttpRequestProxy.requestEncoding));
      params.append("&");
      }

      if (params.length() > 0) {
          params = params.deleteCharAt(params.length() - 1);
      }
      
      URL url = new URL(reqUrl);
      url_con = (HttpURLConnection) url.openConnection();
      url_con.setRequestMethod("POST");
      System.setProperty("sun.net.client.defaultConnectTimeout", String
              .valueOf(HttpRequestProxy.connectTimeOut));// (单位[dan
                                                          // wei]:毫秒)jdk1.4换成这个,连接[lian
                                                          // jie]超时[chao
                                                          // shi]
      System.setProperty("sun.net.client.defaultReadTimeout", String
              .valueOf(HttpRequestProxy.readTimeOut)); // (单位[dan
                                                          // wei]:毫秒)jdk1.4换成这个,读操作超时[chao
                                                          // shi]
      // url_con.setConnectTimeout(5000);//(单位[dan wei]:毫秒)jdk
      // 1.5换成这个,连接[lian jie]超时[chao shi]
      // url_con.setReadTimeout(5000);//(单位[dan wei]:毫秒)jdk
      // 1.5换成这个,读操作超时[chao shi]
      url_con.setDoOutput(true);
      byte[] b = params.toString().getBytes();
      url_con.getOutputStream().write(b, 0, b.length);
      url_con.getOutputStream().flush();
      url_con.getOutputStream().close();
      
      InputStream in = url_con.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(in,
              recvEncoding));
      String tempLine = rd.readLine();
      StringBuffer tempStr = new StringBuffer();
      String crlf = System.getProperty("line.separator");
      while (tempLine != null) {
          tempStr.append(tempLine);
          tempStr.append(crlf);
          tempLine = rd.readLine();
      }
      responseContent = tempStr.toString();
      rd.close();
      in.close();
      

      } catch (IOException e) {
      logger.error("网络[wang luo]故障[gu zhang]", e);
      } finally {

      if (url_con != null) {
          url_con.disconnect();
      }
      

      }
      return responseContent;
      }

    /**

    • @return 连接[lian jie]超时chao shi
    • @see com.hengpeng.common.web.HttpRequestProxy#connectTimeOut */ public static int getConnectTimeOut() { return HttpRequestProxy.connectTimeOut; }

    /**

    • @return 读取[du qu]数据[shu ju]超时chao shi
    • @see com.hengpeng.common.web.HttpRequestProxy#readTimeOut */ public static int getReadTimeOut() { return HttpRequestProxy.readTimeOut; }

    /**

    • @return 请求[qing qiu]编码[bian ma]
    • @see com.hengpeng.common.web.HttpRequestProxy#requestEncoding */ public static String getRequestEncoding() { return requestEncoding; }

    /**

    • @param connectTimeOut
    • 连接[lian jie]超时chao shi
    • @see com.hengpeng.common.web.HttpRequestProxy#connectTimeOut */ public static void setConnectTimeOut(int connectTimeOut) { HttpRequestProxy.connectTimeOut = connectTimeOut; }

    /**

    • @param readTimeOut
    • 读取[du qu]数据[shu ju]超时chao shi
    • @see com.hengpeng.common.web.HttpRequestProxy#readTimeOut */ public static void setReadTimeOut(int readTimeOut) { HttpRequestProxy.readTimeOut = readTimeOut; }

    /**

    • @param requestEncoding
    • 请求[qing qiu]编码[bian ma]
    • @see com.hengpeng.common.web.HttpRequestProxy#requestEncoding */ public static void setRequestEncoding(String requestEncoding) { HttpRequestProxy.requestEncoding = requestEncoding; }

    public static void main(String[] args) {
    Map map = new HashMap();
    map.put("actionType", "1");
    map.put("issueId", "33");
    String temp = HttpRequestProxy.doGet(
    "http://localhost/TransData", map, "GBK");
    System.out.println("返回的消息[xiao xi]是:" + temp);

    }
    }[/color]

最后mian方法中这段
String temp = HttpRequestProxy.doGet("http://localhost/TransData", map, "GBK");
里面的URL是我另外新建的一个web工程,名为TransData。在TransData工程中的index.jsp页面我这样写:
[color=green]<%
String p1 = request.getParameter("actionType");
String p2 = request.getParameter("issueId");
System.out.println("p1:"+p1);
System.out.println("p2:"+p2);
%>[/color]

但是发现我拿不到参数。
就把提交的URL改为提交到servlet:
String temp = HttpRequestProxy.doGet("http://localhost/TransData/a.do", map, "GBK");
在servlet的doPost方法中这样写:
[color=green] String p1 = req.getParameter("actionType");
String p2 = req.getParameter("issueId");
System.out.println(p1);
System.out.println(p2);[/color]

这样打印p1,p2发现可以拿到值。这是为什么呢,为什么在jsp中拿不到参数,在servlet中却可以拿到?

  • 写回答

1条回答

  • CaiHuajiang 2010-11-16 17:57
    关注

    可能http://localhost/TransData到index页面中出现是forward跳转导致参数丢失吧

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退