How to send PUT, DELETE HTTP request in HttpURLCon

2019-01-02 22:10发布

I want to know if it is possible to send PUT, DELETE request (practically) through java.net.HttpURLConnection to HTTP-based URL.

I have read so many articles describing that how to send GET, POST, TRACE, OPTIONS requests but I still haven't found any sample code which successfully performs PUT and DELETE requests.

9条回答
你好瞎i
2楼-- · 2019-01-02 22:43

I would recommend Apache HTTPClient.

查看更多
闹够了就滚
3楼-- · 2019-01-02 22:47
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;
}

Then in your code :

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
}
查看更多
别忘想泡老子
4楼-- · 2019-01-02 22:52

there is a simple way for delete and put request, you can simply do it by adding a "_method" parameter to your post request and write "PUT" or "DELETE" for its value!

查看更多
登录 后发表回答