我想知道是否可以通過java.net.HttpURLConnection
發送PUT,DELETE請求(實際上)到基於HTTP的URL。如何在HttpURLConnection中發送PUT,DELETE HTTP請求?
我已經閱讀了很多文章描述如何發送GET,POST,TRACE,OPTIONS請求,但是我仍然沒有找到任何成功執行PUT和DELETE請求的示例代碼。
我想知道是否可以通過java.net.HttpURLConnection
發送PUT,DELETE請求(實際上)到基於HTTP的URL。如何在HttpURLConnection中發送PUT,DELETE HTTP請求?
我已經閱讀了很多文章描述如何發送GET,POST,TRACE,OPTIONS請求,但是我仍然沒有找到任何成功執行PUT和DELETE請求的示例代碼。
我會推薦Apache HTTPClient。
要執行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 DELETE:
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();
這是如何活像ked對我來說:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
UrlConnection是一個尷尬的API工作。 HttpClient是目前爲止最好的API,它可以讓你免除時間尋找如何完成某些東西,比如這個stackoverflow問題。我在幾個REST客戶端中使用jdk HttpUrlConnection後寫這個。 此外,當涉及到可伸縮性功能(如線程池,連接池等)時,HttpClient更優越
我同意@adietisheim和其他人的建議HttpClient。
我花了很多時間嘗試使用HttpURLConnection進行一個簡單的調用來休息服務,它並沒有讓我相信我,之後我嘗試了使用HttpClient,它確實更容易,更易於理解和更好。
的代碼示例,使認沽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);
在你的代碼
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
}
對於做正確的HTML看跌期權,你會必須用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();
您能告訴我們您嘗試使用的代碼嗎? – akarnokd 2009-06-26 20:07:54