http 네 가지 요청(get/post/delete/put)
12417 단어 자바 백 엔 드
2.방법의 예 는 다음 과 같다.
package com.cmos.clbim.web.util;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.cmos.core.logger.Logger;
import com.cmos.core.logger.LoggerFactory;
import net.sf.json.JSONObject;
public class HttpClientUtil {
private static Logger LOGGER = LoggerFactory.getActionLog(HttpClientUtil.class);
private static final String APPLICATION_JSON = "application/json";
// private static final String APPLICATION_JSON = "application/json;charset="+"\""+"UTF-8"+"\"";
// private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
/**
*
* @Title : httpPost
* @Description: TODO
* @param url
* @param jsonObject
* @return : String
* @author :
* Create Date : 2017-9-21 8:51:09
* @throws
*/
public static String httpPost(String url, String jsonObject) {
CloseableHttpClient httpClient = null;
Map resultMap = new HashMap();
resultMap.put("errorMsg", " ");
JSONObject js = JSONObject.fromObject(resultMap);
String result = "";
try {
LOGGER.info("httpPost => ***--------------- url:------------------------------------"+url);
LOGGER.info("httpPost => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
LOGGER.info("httpPost => ***--------------- json--------------------------"+jsonObject);
//
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(40000)
.setConnectTimeout(40000)
.setConnectionRequestTimeout(40000)
.build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
// httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
HttpPost httpPost = new HttpPost(url);
// hearder
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
// StringEntity se = new StringEntity(encoderJson);
// StringEntity se = new StringEntity(json);
// StringEntity se = new StringEntity(jsonObject,APPLICATION_JSON,"utf-8");
StringEntity se = new StringEntity(jsonObject, ContentType.APPLICATION_JSON);
// se.setContentType(CONTENT_TYPE_TEXT_JSON);
// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
httpPost.setConfig(requestConfig);
httpPost.setEntity(se);
HttpResponse response;
response = httpClient.execute(httpPost);
//
int flag = response.getStatusLine().getStatusCode();
if(flag == 200){
LOGGER.info("httpPost => ***--------------- ------------***");
//
// , response.getEntity().getContent() InputStream
//
//result=new String(result.getBytes("ISO-8859-1"),"GBK");// GBK
result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
}else{
result = js.toString();
LOGGER.info("httpPost => ***--------------- ------------***");
}
} catch (ClientProtocolException e) {
result = js.toString();
LOGGER.error("httpPost => ***--------------- ------------ClientProtocolException",e);
} catch (IOException e) {
result = js.toString();
LOGGER.error("httpPost => ***--------------- ------------IOException",e);
}finally{
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("httpPost => "+ e);
}
}
}
LOGGER.info("httpPost => ***--------------- ------------------------***"+result);
return result;
}
/**
*
* @Title : httpPut
* @Description: TODO
* @param url
* @param jsonObject
* @return : String
* @author :
* Create Date : 2017-9-22 11:28:26
*/
public static String httpPut(String url, String jsonObject) {
CloseableHttpClient httpClient = null;
Map resultMap = new HashMap();
resultMap.put("errorMsg", " ");
JSONObject js = JSONObject.fromObject(resultMap);
String result = "";
try {
LOGGER.info("httpPut => ***--------------- url:------------------------------------"+url);
LOGGER.info("httpPut => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
LOGGER.info("httpPut => ***--------------- json--------------------------"+jsonObject);
//
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(40000)
.setConnectTimeout(40000)
.setConnectionRequestTimeout(40000)
.build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
HttpPut httpPut = new HttpPut(url);
// hearder
httpPut.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
StringEntity se = new StringEntity(jsonObject, ContentType.APPLICATION_JSON);
httpPut.setConfig(requestConfig);
httpPut.setEntity(se);
HttpResponse response;
response = httpClient.execute(httpPut);
//
int flag = response.getStatusLine().getStatusCode();
if(flag == 200){
LOGGER.info("httpPut => ***--------------- ------------***");
result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
}else{
result = js.toString();
LOGGER.info("httpPut => ***--------------- ------------***");
}
} catch (ClientProtocolException e) {
result = js.toString();
LOGGER.error("httpPut => ***--------------- ------------ClientProtocolException",e);
} catch (IOException e) {
result = js.toString();
LOGGER.error("httpPut => ***--------------- ------------IOException",e);
}finally{
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("httpPut => "+e);
}
}
}
LOGGER.info("httpPut => ***--------------- ------------------------***"+result);
return result;
}
/**
*
* @Title : httpGet
* @Description: TODO
* @param url Rest API URL
* @return : String
* @author :
* Create Date : 2017-9-22 4:52:06
*/
public static String httpGet(String url) {
CloseableHttpClient httpClient = null;
Map resultMap = new HashMap();
resultMap.put("errorMsg", " ");
JSONObject js = JSONObject.fromObject(resultMap);
String result = "";
try {
LOGGER.info("httpPut => ***--------------- url:------------------------------------"+url);
LOGGER.info("httpPut => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
//
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(40000)
.setConnectTimeout(40000)
.setConnectionRequestTimeout(40000)
.build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
HttpGet httpGet = new HttpGet(url);
// hearder
httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
httpGet.setConfig(requestConfig);
HttpResponse response;
response = httpClient.execute(httpGet);
//
int flag = response.getStatusLine().getStatusCode();
if(flag == 200){
LOGGER.info("httpGet => ***--------------- ------------***");
result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
}else{
result = js.toString();
LOGGER.info("httpGet => ***--------------- ------------***");
}
} catch (ClientProtocolException e) {
result = js.toString();
LOGGER.error("httpGet => ***--------------- ------------ClientProtocolException",e);
} catch (IOException e) {
result = js.toString();
LOGGER.error("httpGet => ***--------------- ------------IOException",e);
}finally{
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("httpGet => "+ e);
}
}
}
LOGGER.info("httpGet => ***--------------- ------------------------***"+result);
return result;
}
public static String httpDelete(String url) {
CloseableHttpClient httpClient = null;
Map resultMap = new HashMap();
resultMap.put("errorMsg", " ");
JSONObject js = JSONObject.fromObject(resultMap);
String result = "";
try {
LOGGER.info("httpDelete => ***--------------- url:------------------------------------"+url);
LOGGER.info("httpDelete => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
//
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(40000)
.setConnectTimeout(40000)
.setConnectionRequestTimeout(40000)
.build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
HttpDelete httpDelete = new HttpDelete(url);
// hearder
httpDelete.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
httpDelete.setConfig(requestConfig);
HttpResponse response;
response = httpClient.execute(httpDelete);
//
int flag = response.getStatusLine().getStatusCode();
if(flag == 200){
LOGGER.info("httpDelete => ***--------------- ------------***");
result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
}else{
result = js.toString();
LOGGER.info("httpDelete => ***--------------- ------------***");
}
} catch (ClientProtocolException e) {
result = js.toString();
LOGGER.error("httpDelete => ***--------------- ------------ClientProtocolException",e);
} catch (IOException e) {
result = js.toString();
LOGGER.error("httpDelete => ***--------------- ------------IOException",e);
}finally{
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("httpDelete => "+ e);
}
}
}
LOGGER.info("httpDelete => ***--------------- ------------------------***"+result);
return result;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
모드 1영역 구동 디자인 domain - driven design 장면 에서 의 문 제 를 해결 하기 위해 형 성 된 모델 을 사용 한 다음 에 이 모델 로 업무 문 제 를 해결한다.반복 노동 경험 에 근거 하여 우 리 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.