답변:
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();
delete. 이 코드를 여기에서 실행하면 실제로 아무 일도 일어나지 않으며 요청이 전송되지 않습니다. post요청을 할 때와 같은 상황 이지만 요청 httpCon.getContent()을 트리거하는 예 를 사용할 수 있습니다 . 그러나 httpCon.connect()내 컴퓨터에서 아무것도 트리거하지 않습니다 :-)
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);
HttpURLConnection를 작동시키는 데 많은 시간을 보냈지 만 이상한 오류가 계속 발생했습니다 cannot retry due to server authentication, in streaming mode. 당신의 조언을 따르면 나를 위해 일했습니다. 나는 이것이 질문에 정확하게 대답하지는 않는다는 HttpURLConnection것을 알고 있습니다.
HTML에서 PUT을 올바르게 수행하려면 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();
}
나머지 템플릿조차도 옵션이 될 수 있습니다.
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();
삭제 및 넣기 요청에 대한 간단한 방법 _method이 있습니다. 게시 요청에 " "매개 변수를 추가하고 해당 값으로 " PUT"또는 " DELETE"를 쓰면됩니다 .