有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

网络编程在启动时打开http url连接,然后在Java中写入参数/值

我想用java。net api打开url并获取响应。这个url每天都会以数百万次的速度到达同一个来源,每次都有不同的参数。这必须非常快,因为tps的数量非常高。我想知道是否有可能在启动时打开一次连接,然后在每次新点击时写入参数值

我希望这样做

HttpURLConnection connection=null;
public void init(ServletConfig config) throws ServletException {
                       Url url1 = new URL("http://127.0.0.1:9081/charging");
            long start = System.currentTimeMillis();
            long stop=0;
            connection = (HttpURLConnection) url1.openConnection();
            connection.setDoOutput(true);
             connection.setDoInput(true);
             connection.setInstanceFollowRedirects(false); 
             connection.setRequestMethod("POST"); 
}

并将这个连接对象传递给方法

public String openCharging(HttpURLConnection connection, ParamBean bean)
{
String response=null;
  String paramstring="ChargingMode="+bean.getMode+"&ChargingAmount="+bean.getEUP+.;.and so on
  BufferedReader in=null;
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
    wr.writeBytes(paramstring);
    wr.flush();
    try 
    {
    in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                if(in!=null)
                {
                    response = in.readLine();
                }
            } 
            catch (Exception e) 
            {}finally{//close all except connection object}         
}

这需要尽可能低的潜在性,但我对高性能java的了解有限。 任何帮助都将不胜感激

//任何其他更好的解决方案也是受欢迎的+apache替代方案


共 (1) 个答案

  1. # 1 楼答案

    不,不是

    然而,您似乎不知道HttpURLConnection在幕后进行连接池,因此只要您不调用disconnect(),并足够频繁地使用URL,连接开销就已经分摊