Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build URL in java

Tags:

java

url

build

Trying to build http://IP:4567/foldername/1234?abc=xyz. I don't know much about it but I wrote below code from searching from google:

import java.net.MalformedURLException; import java.net.URI; import java.net.URL;  public class MyUrlConstruct {      public static void main(String a[]){          try {             String protocol = "http";             String host = "IP";             int port = 4567;             String path = "foldername/1234";             URL url = new URL (protocol, host, port, path);             System.out.println(url.toString()+"?");         } catch (MalformedURLException ex) {             ex.printStackTrace();         }     } } 

I am able to build URL http://IP:port/foldername/1234?. I am stuck at query part. Please help me to move forward.

like image 283
rrr ppp Avatar asked Sep 14 '16 20:09

rrr ppp


People also ask

How do you create a URL in Java?

In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.

How do you link a URL in Java?

connect method is called. When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com : try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL.

How do you query a URL in Java?

URL getQuery() method in Java with Examples The getQuery() function is a part of URL class. The function getQuery() returns the Query of a specified URL. Return Type: The function returns String Type Query of a specified URL.


2 Answers

You can just pass raw spec

new URL("http://IP:4567/foldername/1234?abc=xyz"); 

Or you can take something like org.apache.http.client.utils.URIBuilder and build it in safe manner with proper url encoding

URIBuilder builder = new URIBuilder(); builder.setScheme("http"); builder.setHost("IP"); builder.setPath("/foldername/1234"); builder.addParameter("abc", "xyz"); URL url = builder.build().toURL(); 
like image 56
vsminkov Avatar answered Oct 05 '22 17:10

vsminkov


Use OkHttp

There is a very popular library named OkHttp which has been starred 20K times on GitHub. With this library, you can build the url like below:

import okhttp3.HttpUrl;  URL url = new HttpUrl.Builder()     .scheme("http")     .host("example.com")     .port(4567)     .addPathSegments("foldername/1234")     .addQueryParameter("abc", "xyz")     .build().url(); 

Or you can simply parse an URL:

URL url = HttpUrl.parse("http://example.com:4567/foldername/1234?abc=xyz").url(); 
like image 38
Tyler Liu Avatar answered Oct 05 '22 18:10

Tyler Liu