JAVA 代码

导入 jar 包

httpclient-4.2.3.jar
httpcore-4.2.2.jar

java 代码

/**
 * url+param 拼接字符串的发送发送,post
 * @param url
 * @param param param 拼接字符串方式
 * @return
 */
public static String execute(String url,String param){

    if (url == null || url.length()==0 || param==null || param.length()==0) {
        return "";
    }
    try {
        HttpPost httpPost = new HttpPost(url);  
        StringEntity stringEntity = new StringEntity(param,"utf-8");//param 参数,拼接的一串字符串  
        stringEntity.setContentType("application/x-www-form-urlencoded");// 默认的, 写不写无所谓  
        httpPost.setEntity(stringEntity);  
        HttpClient client = new DefaultHttpClient();   
        HttpParams params = client.getParams();
        // 请求超时
        HttpConnectionParams.setConnectionTimeout(params, 3 * 1000);
        // 读取超时
        HttpConnectionParams.setSoTimeout(params, 5 * 1000);
        String result=sendRequest(client, httpPost, 3);// 设置 3 次请求
        return result;
    } catch (Exception e){

    }  
    return "";
}




/**
 * add, 设置多次请求
 * @param client
 * @param request
 * @param count
 * @return
 */
static String sendRequest(HttpClient client, HttpUriRequest request, int count) {
    HttpResponse response=null;
    HttpEntity entity =null;
    String res=null;
    for (int i = 0; i < count; i++) {
        try {
            response = client.execute(request);
            entity = response.getEntity();
            if (entity != null) {
                res= EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);//release
                break; 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return res;   
}

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:PipeSoloSymWide 等,欢迎大家加入,贡献开源。

    2818 引用 • 4207 回帖 • 644 关注
  • HTTP
    37 引用 • 99 回帖
感谢    关注    收藏    赞同    反对    举报    分享