我想知道是否可以通过发送PUT,DELETE请求(几乎) java.net.HttpURLConnection
,以基于HTTP的URL。
我已经看了这么多文章描述了如何发送GET,POST,TRACE,OPTIONS请求,但我还没有发现它成功地执行PUT和DELETE请求任何示例代码。
我想知道是否可以通过发送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 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();
这是如何为我工作:
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的人休息。
我花时间试图做一个简单的调用REST服务与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);
URLConnection的是一个尴尬的API一起工作。 HttpClient的是迄今为止更好的API,它会从松动的时间来寻找如何实现某些事情像这个计算器问题说明完美饶了你。 我已经使用了JDK HttpURLConnection的几个REST客户端后写这个。 此外,当涉及到可扩展性功能(如线程池,连接池等)的HttpClient优于
对于做正确的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();
}
我会建议阿帕奇了HTTPClient。
即使休息模板可以是一个选项:
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
”为它的价值!