Reputation: 15322
Boss wants us to send a HTTP GET with parameters in the body. I can't figure out how to do this using org.apache.commons.httpclient.methods.GetMethod or java.net.HttpURLConnection;.
GetMethod doesn't seem to take any parameters, and I'm not sure how to use HttpURLConnection for this.
Upvotes: 10
Views: 17865
Reputation: 7838
Using java.net.http.HttpRequest
, when building one with a RequestBuilder instead of using the .GET()
method that doesn't take paramenters, user the .method(method, bodyPublisher)
HttpClient clientFwd = HttpClient.newHttpClient();
HttpRequest get = HttpRequest.newBuilder()
.uri(URI.create(YOURURI))
//GET, POST, PUT,..
.method("GET", HttpRequest.BodyPublishers.ofString(bodyGet))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer "+TOKEN)
.build();
Then get.send()
your HttpRequest to get your response.
Upvotes: 1
Reputation: 10564
You can extends the HttpEntityEnclosingRequestBase class to override the inherited org.apache.http.client.methods.HttpRequestBase.getMethod() but by fact HTTP GET does not support body request and maybe you will experience trouble with some HTTP servers, use at your own risk :)
public class MyHttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public final static String GET_METHOD = "GET";
public MyHttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
public MyHttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return GET_METHOD;
}
}
then
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpEntityGet {
public static void main(String[] args) {
try {
HttpClient client = new DefaultHttpClient();
MyHttpGetWithEntity e = new MyHttpGetWithEntity("http://....");
e.setEntity(new StringEntity("mystringentity"));
HttpResponse response = client.execute(e);
System.out.println(IOUtils.toString(response.getEntity().getContent()));
} catch (Exception e) {
System.err.println(e);
}
}
}
Upvotes: 4
Reputation: 9655
HTTP GET method should NEVER have a body section. You can pass your parameters using URL query string or HTTP headers.
If you want to have a BODY section. Use POST or other methods.
Upvotes: 3