如何使用HttpClient和Servlet处理多个请求

时间:2017-11-22 01:20:59

标签: java http servlets httpclient

我试图做我的论文,但我遇到了一些问题。我不知道如何解决servlet上的多重请求。你能帮助我吗?请 这是我在httpclient的代码

public double similarity(BasicDBObject json, String model) 
        throws ClientProtocolException, IOException {
    double value = 0.0;
    try {
         HttpClient httpClient = new DefaultHttpClient();
         HttpPost httpPost = new HttpPost(
                 "http://localhost:8080/SimilarityServices/compare");
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

         nameValuePairs.add(new BasicNameValuePair("param1",json.toString() ));

         nameValuePairs.add(new BasicNameValuePair("param2",model ));

         httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

         HttpResponse response = httpClient.execute(httpPost);

        String res = null;

        HttpEntity data = response.getEntity();

        if (data != null) {

          InputStream instream = data.getContent();

          byte[] bytes = IOUtils.toByteArray(instream);

          res = new String(bytes, "UTF-8");

          instream.close();

        }

        if(res != null)
        {
            value = Double.parseDouble(res);
        }
    }
    catch(Exception e)
    {
        System.out.println("Error 1");
    }

    return value;

}

这是我在Servlet的代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String part1 = request.getParameter("param1"); 
    String part2 = request.getParameter("param2"); 

    BasicDBObject obj = (BasicDBObject) JSON.parse(part1);
    BasicDBObject model = (BasicDBObject) JSON.parse(part2);

    double re = comparation(obj,model);

    response.setContentType("text/html");

    out.println(re);
    out.close();
}

我有一个函数doPost()但是在doPost()中,我调用了doGet()。

我有()如下文

for(int i = 0; i < list.size(); i++) 
    {
        BasicDBObject cur = (BasicDBObject) list.get(i);
        System.out.println(i);
        result.add(similarity(cur,model[0]));
    }

当list.size()&lt; 100,它很好。 但是我的列表大小是500,有时servlet无法接收两个参数(param1和param2)。

你可以帮帮我吗?请。

0 个答案:

没有答案