"JAVA 代码 导入 jar 包 [链接] [链接] java 代码 /** * url+param拼接字符串的发送发送,post * @param url * @param param param拼接字符串方式 * @return */ public static String execute(String url, .."

通过 url 请求获取响应内容 -http 协议

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 等,欢迎大家加入,贡献开源。

    2095 引用 • 3641 回帖 • 619 关注
  • HTTP
    42 引用 • 100 回帖
回帖   
请输入回帖内容...