Bruce
Bruce

Reputation: 35285

Problem generating GET url

I am working on Java. I am calling a GET url on my own machine using Java. Here is the url string with the arguments.

listen.executeUrl("http://localhost/post_message.php?query_string="+str); 

I am taking str as user input.

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 System.out.print("Enter query: ");
 str = br.readLine();

How do I encode str into GET argument. For eg.

str -> test query

url -> http://localhost/post_message.php?query_string=test%20query

Upvotes: 0

Views: 90

Answers (3)

Doctor Kicks
Doctor Kicks

Reputation: 494

String query = URLEncoder.encode(str, "UTF-8").replaceAll("\\+", "%20");

Note that URLEncoder replaces spaces with +, not %20. Here is a detailed discussion of the differences.

Upvotes: 1

mdma
mdma

Reputation: 57777

You will need to encode your query string, e.g.

str = URLEncoder.encode(str, "UTF-8");

You set the second argument to the encoding that your server is configured for.

See URLEncoder.encode

Upvotes: 1

Julien Lebosquain
Julien Lebosquain

Reputation: 41253

Use the encode() method of the java.net.URLEncoder class.

Upvotes: 1

Related Questions