我的HTTPClient连接是否泄漏了套接字?

时间:2015-11-07 13:47:20

标签: java sockets google-app-engine http-post httpclient

我在谷歌应用引擎上部署了一个使用Apache HTTPClient的应用。最近,当应用程序获得更多流量时,我已经开始遇到超出套接字配额的异常。

是个例外
com.google.apphosting.api.ApiProxy$OverQuotaException: The API call remote_socket.SetSocketOptions() required more quota than is available.

我联系了App Engine团队,他们希望我检查我的应用程序是否漏了插座。

CloseableHttpClient httpclient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost("http://www.spark.com");

List <NameValuePair> nvps = new ArrayList <NameValuePair>();

nvps.add(new BasicNameValuePair("param1", "val1"));
nvps.add(new BasicNameValuePair("param2", "val2"));

httpPost.setEntity(new UrlEncodedFormEntity(nvps));

CloseableHttpResponse response = httpclient.execute(httpPost);
Document doc = null;
try {
    HttpEntity entity = response.getEntity();
    doc = Jsoup.parse(entity.getContent(), "UTF-8", "");
    EntityUtils.consume(entity);
} finally {
    response.close();
    httpclient.close();
}

这就是我的http连接代码。我做错了什么可能导致插座泄漏?我能做得更好吗?

1 个答案:

答案 0 :(得分:0)

这项工作对我来说:

HttpParams httpParameters = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
    HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);

       HttpClient httpclient = new DefaultHttpClient(httpParameters);
      // HttpPost httppost = new HttpPost("http://rafsanjan.uni-azad.my.com/json/darkhasr.php?shdaneshjo="+value_id+"&moavenat="+value_seaction+"&darkhast="+zir_item+"&startdate=test&tozih="+ value_descration);  //???
       try {
           URIBuilder builder = new URIBuilder();
           builder.setScheme("http")
                   .setHost("app.my.ac.com")
                   .setPort(1180)
                   .setPath("/json2/darkhasr.php")
                   .addParameter("shdaneshjo", value_id)
                   .addParameter("moavenat", value_seaction)
                   .addParameter("darkhast", value_item)
                   .addParameter("startdatet", "0")
                   .addParameter("tozih", value_descration)
                   .build();
           // .fragment("section-name");
           String myUrl = builder.toString();
           Log.d("url=>",myUrl);

           HttpPost httppost = new HttpPost(myUrl);

           ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(8);
           //nameValuePairs.add(new BasicNameValuePair("name", name));
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
           HttpResponse response = httpclient.execute(httppost);
           HttpEntity resEntity = response.getEntity();  
           Log.d("RESPONSE",EntityUtils.toString(resEntity));

       }
       catch(Exception e)
       {
           Log.e("log_tag", "Error:  "+e.toString());
       }