java中delete请求_如何在HttpURLConnection中发送PUT,DELETE HTTP请求?

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值