Answers:
要执行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();
delete
。当我按原样运行此代码时,什么也没有发生,因此不发送请求。同样的情况发生在我执行post
请求时,但是在这里我可以使用例如httpCon.getContent()
触发请求的方法。但是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);
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();
}
甚至Rest Template也是一个选择:
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
”即可。