Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection with Parameters

Tags:

java

I have a URL which I pass in that looks like this

http://somecompany.com/restws/ebi/SVI/4048/?Name=Tra&Brand=Software: WebSphere - Open App Servers

It does not like the 2nd parameter (Brand). From a browser this querystring above works fine but as soon as I execute in Java, it fails. When I change the webservice to accept a single parameter, then this URL works fine

http://somecompany.com/restws/ebi/SVI/4048/?Name=Tra

It seems java is having issues with the 2nd parameter. I have tried escape characters and everything else I can think of but nothing seems to work. Please Help!

String uri = "somecompany.com/restws/ebi/SVI/4048/?Name=" 
           + name+ "&Brand=Software: WebSphere - Open App Servers";

URL url;

try {
    url = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/xml");
}
...
like image 413
Bryan Avatar asked Feb 20 '23 16:02

Bryan


2 Answers

Try url encoding your parameters.

Something like this:

String uri = "somecompany.com/restws/ebi/SVI/4048/?Name=" +name+ "&Brand=";
uri = URLEncoder.encode("Software: WebSphere - Open App Servers", "utf-8");
like image 56
Pablo Santa Cruz Avatar answered Feb 22 '23 08:02

Pablo Santa Cruz


I'd perhaps use a library that can handle HTTP parameters properly and provide suitable encoding etc. See HttpComponents and the tutorial for more info.

like image 45
Brian Agnew Avatar answered Feb 22 '23 06:02

Brian Agnew