How to pass request parameters in java using Http client

I use the GET REST call in java using the given code, but I get the error code: 404 ie Not found. But when I use the same URL in the browser, I get the output and it works fine. I am new to JAVA. Perhaps I am passing the request parameters incorrectly, but I am not receiving it. I work in NETBEANS 7.1.2. Please help.

    import java.io.IOException;
    import java.io.OutputStreamWriter; 
    import java.net.HttpURLConnection; 
    import java.net.URL; 
       public class Test {
          private static String ENDPOINT ="http://wisekar.iitd.ernet.in/active/api_resources.php/method/mynode?";
          public static void main(String[] args) throws IOException 
          { 
              URL url = new URL(ENDPOINT + "key=" + "mykey"  );
              HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); 
              httpCon.setDoOutput(true);
              httpCon.setRequestMethod("GET");
             OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream());
             System.out.println(httpCon.getResponseCode());
             System.out.println(httpCon.getResponseMessage());
             out.close(); 
          }
   }

here mykey is the key given to me on the website.

I also want to print the response message in the output window or console. Since I want to keep it in the future for some extraction. Please, help.

+5
source share
1 answer

. . 401-Unauthorised URL- , VPN - .

private static String ENDPOINT ="http://google.com"; 

200-OK.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

       public class Test {
          private static String ENDPOINT ="http://wisekar.iitd.ernet.in/active/api_resources.php/method/mynode";
          public static void main(String[] args) throws IOException 
          { 
              String url = ENDPOINT;
              String charset = "UTF-8";
              String param1 = "mykey";

              String query = String.format("key=%s", 
                   URLEncoder.encode(param1, charset));
              java.net.URLConnection connection = new URL(url + "?" + query).openConnection();
              connection.setRequestProperty("Accept-Charset", charset);
              if ( connection instanceof HttpURLConnection)
              {
                 HttpURLConnection httpConnection = (HttpURLConnection) connection;
                 System.out.println(httpConnection.getResponseCode());
                 System.out.println(httpConnection.getResponseMessage());
              }
              else
              {
                 System.err.println ("error!");
              }
          }
   }
+5

All Articles