Apache HttpClient GET with body

后端 未结 4 1571
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 23:45

I am trying to send an HTTP GET with a json object in its body. Is there a way to set the body of an HttpClient HttpGet? I am looking for the equivalent of HttpPost#setEntit

相关标签:
4条回答
  • 2020-12-05 23:53

    Using torbinsky's answer I created the above class. This lets me use the same methods for HttpPost.

    import java.net.URI;
    
    import org.apache.http.client.methods.HttpPost;
    
    public class HttpGetWithEntity extends HttpPost {
    
        public final static String METHOD_NAME = "GET";
    
        public HttpGetWithEntity(URI url) {
            super(url);
        }
    
        public HttpGetWithEntity(String url) {
            super(url);
        }
    
        @Override
        public String getMethod() {
            return METHOD_NAME;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 00:03

    How we can send request uri in this example just like HttpGet & HttpPost ???

     public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase
     {
        public final static String METHOD_NAME = "GET";
        @Override
         public String getMethod() {
             return METHOD_NAME;
         } 
    
            HttpGetWithEntity e = new HttpGetWithEntity(); 
            e.setEntity(yourEntity); 
            response = httpclient.execute(e); 
    }
    
    0 讨论(0)
  • 2020-12-06 00:07

    In addition torbinsky's answer, you can add these constructors to the class to make it easier to set the uri:

    public HttpGetWithEntity(String uri) throws URISyntaxException{
        this.setURI(new URI(uri));
    }
    
    public HttpGetWithEntity(URI uri){
        this.setURI(uri);
    }
    

    The setURI method is inherited from HttpEntityEnclosingRequestBase and can also be used outside the constructor.

    0 讨论(0)
  • 2020-12-06 00:17

    From what I know, you can't do this with the default HttpGet class that comes with the Apache library. However, you can subclass the HttpEntityEnclosingRequestBase entity and set the method to GET. I haven't tested this, but I think the following example might be what you're looking for:

    import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
    
    public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
        public final static String METHOD_NAME = "GET";
    
        @Override
        public String getMethod() {
            return METHOD_NAME;
        }
    }
    

    Edit:

    You could then do the following:

    ...
    HttpGetWithEntity e = new HttpGetWithEntity();
    ...
    e.setEntity(yourEntity);
    ...
    response = httpclient.execute(e);
    
    0 讨论(0)
提交回复
热议问题