Send HTTP GET headers in Java
I'm interested if it is possible to send HTTP GET headers with Java.
Basically I'm working on a Java program that interfaces with a REST-like web-service. To mimic this I've created a small php file which simply outputs all the variables in $_GET
, this way I can see if my GET header variables are correctly submitted.
In php you can 'send' get variables by using the ?key=value
syntax, however I'm not sure if this works for every web platform. So I thought about sending these (key, value) pairs in the HTTP GET header (if this is not possible, or the wrong way to do it, feel free to point this out!).
I've got the following code, but the response from the server doesn't echo any of the GET variables I send:
public static void Request(String address, Vector<RequestProperty> props){
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder;
try{
url = new URL(address);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
//Add request headers
for(RequestProperty prop : props){
//Here I add the pairs like MyKey = MyValue
connection.addRequestProperty(prop.key, prop.value);
}
connection.setReadTimeout(15000);
connection.connect();
reader = new Buffere开发者_如何转开发dReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while((line = reader.readLine()) != null){
System.out.println(line);
}
}
catch(Exception ex){
ex.printStackTrace();
}
The parameters of a GET
request belong in the URL (i.e. using the ?key=value
syntax).
You could put other information in headers, but that won't be interpreted as being the same as the arguments (i.e. you need to interpret it differently on the server side) and is rarely done for general-purpose arguments.
I think you may have a couple of concepts a bit confused. In PHP $_GET
provides access to GET parameters, not HTTP headers. But sending a GET parameter is easy, just follow the same ?key=value
syntax that you are used to from PHP. It works just as well in Java (or anywhere else, for that matter).
Headers a different thing entirely, and are managed the same way regardless of whether the request parameters are sent using GET or POST. For most applications you will not need to set or retrieve any custom HTTP header values.
精彩评论