HttpURLConnection에서 PUT, DELETE HTTP 요청을 보내는 방법은 무엇입니까?
PUT, DELETE 요청을 (실제로) java.net.HttpURLConnection
HTTP 기반 URL 로 보낼 수 있는지 알고 싶습니다 .
GET, POST, TRACE, OPTIONS 요청을 보내는 방법을 설명하는 많은 기사를 읽었지만 여전히 PUT 및 DELETE 요청을 성공적으로 수행하는 샘플 코드를 찾지 못했습니다.
HTTP PUT을 수행하려면
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
HTTP 삭제를 수행하려면 다음을 수행하십시오.
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
이것이 나를 위해 일한 방법입니다.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
public HttpURLConnection getHttpConnection(String url, String type){
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url);
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "Your Encoding");
con.setRequestProperty("Content-Type", "Your Encoding");
}catch(Exception e){
logger.info( "connection i/o failed" );
}
return con;
}
그런 다음 코드에서 :
public void yourmethod(String url, String type, String reqbody){
HttpURLConnection con = null;
String result = null;
try {
con = conUtil.getHttpConnection( url , type);
//you can add any request body here if you want to post
if( reqbody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(reqbody);
out.flush();
out.close();
}
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String temp = null;
StringBuilder sb = new StringBuilder();
while((temp = in.readLine()) != null){
sb.append(temp).append(" ");
}
result = sb.toString();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
//result is the response you get from the remote side
}
@adietisheim 및 HttpClient를 제안하는 다른 사람들과 동의합니다.
나는 HttpURLConnection으로 서비스를 휴식시키기 위해 간단한 호출을 시도하는 데 시간을 보냈고 그것을 확신하지 못했고 그 후에 HttpClient로 시도했으며 더 쉽고 이해하기 쉽고 훌륭했습니다.
Put http 호출을하는 코드의 예는 다음과 같습니다.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(URI);
StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);
putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);
UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior
For doing a PUT in HTML correctly, you will have to surround it with try/catch:
try {
url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Even Rest Template can be an option :
String payload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?<CourierServiceabilityRequest>....";
RestTemplate rest = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/xml");
headers.add("Accept", "*/*");
HttpEntity<String> requestEntity = new HttpEntity<String>(payload, headers);
ResponseEntity<String> responseEntity =
rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);
responseEntity.getBody().toString();
there is a simple way for delete and put request, you can simply do it by adding a "_method
" parameter to your post request and write "PUT
" or "DELETE
" for its value!
I would recommend Apache HTTPClient.
참고URL : https://stackoverflow.com/questions/1051004/how-to-send-put-delete-http-request-in-httpurlconnection
'Programming' 카테고리의 다른 글
Greenlet Vs. (0) | 2020.07.03 |
---|---|
이메일을 보내는 앱을 개발하고 테스트하는 방법 (테스트 데이터로 다른 사람의 사서함을 채우지 않고)? (0) | 2020.07.03 |
CheckBoxFor가 추가 입력 태그를 렌더링하는 이유는 무엇이며 FormCollection을 사용하여 값을 얻는 방법은 무엇입니까? (0) | 2020.07.03 |
pem 키를 ssh-rsa 형식으로 변환 (0) | 2020.07.03 |
SVN 업그레이드 작업 사본 (0) | 2020.07.03 |