HTTP post请求 get请求 java

lipLanguage是实体类
String jsonObject = new Gson().toJson(lipLanguage);

public static String post_raw(String httpUrl, String content,String charset, int outTime) throws Exception { 
	String result = null;
	if(charset==null||charset.isEmpty()){
		charset = "UTF-8";
	}
	
	HttpPost httppost = new HttpPost(httpUrl);
    try {
		//设置请求和传输超时时间
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(outTime).setConnectTimeout(outTime).build();
		httppost.setConfig(requestConfig);
		
    	StringEntity entity = new StringEntity(content, charset);

// entity.setContentType(contentType+";charset="+charset);
// entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, “application/json”));
httppost.setEntity(entity);
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(response.getEntity(),charset);
}
}else{
result = String.valueOf(statusCode); //把HTTP编码返回
}
}finally {
httppost.releaseConnection();
}
return result;
}

注释:
httpUrl是url路径
content是发送类容,这个地方就是jsonObject

下面是get请求
/**
* 发送 get请求
*/
public static String get(String httpUrl, String charset) {
String resutl = “”;
if (httpUrl == null || httpUrl.equals("")|| !httpUrl.startsWith(“http”)) {
return resutl;
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet(httpUrl);
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(new Integer(15000)).setConnectTimeout(new Integer(15000)).build();
httpget.setConfig(requestConfig);
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 响应状态
int httpStatusCode = response.getStatusLine().getStatusCode();
if(httpStatusCode != HttpStatus.SC_OK){
log.warn(“访问:”+httpUrl+“错误,httpStatusCode=”+httpStatusCode);
return resutl;
}
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 响应内容
resutl = EntityUtils.toString(entity, charset);
}
} finally {
response.close();
}
} catch (Exception e) {
resutl = e.getMessage();
log.warn(“访问:”+httpUrl+“异常:”+e.getMessage());
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resutl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值