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;
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于