300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java 请求http get_java http get/post请求

java 请求http get_java http get/post请求

时间:2024-03-16 18:08:50

相关推荐

java 请求http get_java http get/post请求

/*** @Description httpPost请求*/

public staticString httpPost(String url, String jsonParam, String userName, String password) {

String responseResult= "";try{

CloseableHttpClient httpClient=HttpClients.createDefault();

RequestConfig requestConfig=RequestConfig.custom()

.setSocketTimeout(300 * 1000)

.setConnectTimeout(300 * 1000)

.build();

HttpPost post= newHttpPost(url);if(StringUtils.isNotBlank(userName) &&StringUtils.isNotBlank(password)){

post.addHeader("Authorization", "Basic " + encode(userName+":"+password));

}

post.setConfig(requestConfig);

post.setHeader("Content-Type","application/json;charset=utf-8");

StringEntity postingString= new StringEntity(jsonParam,"utf-8");

post.setEntity(postingString);

HttpResponse response=httpClient.execute(post);

responseResult=EntityUtils.toString(response.getEntity());

}catch(Exception e){

logger.error(e.getMessage(),e);

}returnresponseResult;

}/*** @Description httpGet请求*/

public static finalString get(String url) {

String result= "";

HttpClient client= newHttpClient();

GetMethod method= newGetMethod(url);

method.addRequestHeader("User-Agent", DEFAULT_USER_AGENT);try{

client.executeMethod(method);

result=method.getResponseBodyAsString();

}catch(Exception e) {

logger.error(e.getMessage(),e);

}finally{

method.releaseConnection();

}returnresult;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。