java后台写get或者post请求

java后台写get或者post请求,第1张

java后台写get或者post请求
String url="https://www.baidu.com";
String id=vo.getInfoId();
StringPart infoid=new StringPart("infoid",id ,"utf-8");
Part[] parts= {infoid};
String result = HttpSendUtil.clientPost(url, parts);

public static String clientPost(String url,Part[] parts){
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
post.setRequestHeader("referer", url);
String resutl="";
System.out.println(url);
try {

MultipartRequestEntity mre = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(mre);
int status = client.executeMethod(post);
resutl = post.getResponseBodyAsString();
log.info("POST访问链接:"+url);
log.info("POST访问状态:"+status);
log.info("POST访问结果:"+resutl);
} catch (Exception e) {
log.info("POST访问错误:"+e.getMessage());
e.printStackTrace() ;
}finally{
try {
if (post != null) {
post.releaseConnection();
}
} catch (Exception e) {
log.info("POST访问关闭链接错误:"+e.getMessage());
e.printStackTrace() ;
}
}
return resutl;
}


public static String clientGet(String url,Map paramMap){
String result="";
try {
//创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个uri对象
URIBuilder uriBuilder = new URIBuilder(url);
for(String key : paramMap.keySet()){
//添加参数
uriBuilder.addParameter(key, paramMap.get(key));
}
HttpGet get = new HttpGet(uriBuilder.build());
//执行请求
CloseableHttpResponse response = httpClient.execute(get);
//取响应的结果
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "utf-8");
log.info("GET访问链接:"+url);
log.info("GET访问状态:"+statusCode);
log.info("GET访问结果:"+result);
//关闭httpclient
response.close();
httpClient.close();
} catch (Exception e) {
System.out.println("GET访问错误:"+e.getMessage());
log.info("GET访问错误:"+e.getMessage());
}
return result;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4658989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-06
下一篇 2022-11-06

发表评论

登录后才能评论

评论列表(0条)

保存