How to get the standard input in Java | Examples Java Code Geeks

Malformedurlexception unknown protocol socket что это

I’ m writing a class to run xjc in java. my code goes as follows:

however I get the following error when I run this:

Can anyone help with this please?

41.6k 17 17 gold badges 75 75 silver badges 101 101 bronze badges 131 1 1 gold badge 1 1 silver badge 5 5 bronze badges Have you tried sc.parseSchema(new InputSource(«C:\\Users\\Simran\\Desktop\\books.xsd»)); As I suggested before ?

3 Answers 3

Try append «file://» to the beginning of your file path. But as Bozho proposed, you don’t need an URL here.

41.6k 17 17 gold badges 75 75 silver badges 101 101 bronze badges can anyone give me some link for using xjc through API calls?

This is not a valid URL. It can be made valid by prepending file:// as protocol.

But you don’t need a URL at all. You can pass a Reader (as well as an InputStream ) to the InputSource constructor. So for example:

Моя программа пытается проанализировать XML-строку, используя:

Любые предложения о том, что вызывает эту ошибку?

Обратите внимание: если вы читаете XML файл из файла, вы можете напрямую передать объект File DocumentBuilder.parse() .

В качестве побочного примечания, это шаблон, с которым вы столкнетесь много на Java. Обычно большинство API работают с Streams больше, чем с помощью Strings. Использование Streams означает, что потенциально не все содержимое должно быть загружено в память одновременно, что может быть отличной идеей!

4 Answers 4

Go to Control Panel of Windows and do the followings:

Click Java -> Click «Network Settings. » button under General tab -> Select Direct connection radio -> Click OK

That’s it. Exception could be removed.

34.5k 37 37 gold badges 147 147 silver badges 168 168 bronze badges The question is which «browser setting» is used on Linux as default? Good point keiki. Running linux here. I had proxy set up in Firefox but was launching the JNLP app from chrome and this error was a mystery to me. If you are in Linux Run command ControlPanel and Go to General > Network Settings.. > Direct Connection

This message comes from the use of a proxy server which is not fully set in Internet options (in Internet Explorer).

When a proxy server is set manually, but with the option «use this server for all protocols», Internet Explorer does not fill the «Socks» protocol field with it.

Direct connection works, because you bypass this proxy configuration set in IE. But another way to fix this is to uncheck «use this server for all protocols», and instead paste it in the socks field as well.

Читайте также:  Css стиль кнопок develnext

It should solve the issue without having to bypass the proxy for all Java programs.

However, this is assuming that your proxy server knows what to do with this protocol, and how to direct it to the correct place. If it doesn’t, then you are probably better off trying direct connection.

I have Studio.jnlp file. I tried to open it by double-click. But I found the error as below:

Summary of Exception

Details of Exception

34.5k 37 37 gold badges 147 147 silver badges 168 168 bronze badges What is the (presumably malformed) URL? Post code, error messages and stack trace; not pictures. In my case I just had to disable the proxy on. Firefox (as it is my primary browser)!

4 Answers 4

Go to Control Panel of Windows and do the followings:

Click Java -> Click «Network Settings. » button under General tab -> Select Direct connection radio -> Click OK

That’s it. Exception could be removed.

34.5k 37 37 gold badges 147 147 silver badges 168 168 bronze badges The question is which «browser setting» is used on Linux as default? Good point keiki. Running linux here. I had proxy set up in Firefox but was launching the JNLP app from chrome and this error was a mystery to me. If you are in Linux Run command ControlPanel and Go to General > Network Settings.. > Direct Connection

This message comes from the use of a proxy server which is not fully set in Internet options (in Internet Explorer).

When a proxy server is set manually, but with the option «use this server for all protocols», Internet Explorer does not fill the «Socks» protocol field with it.

Direct connection works, because you bypass this proxy configuration set in IE. But another way to fix this is to uncheck «use this server for all protocols», and instead paste it in the socks field as well.

It should solve the issue without having to bypass the proxy for all Java programs.

However, this is assuming that your proxy server knows what to do with this protocol, and how to direct it to the correct place. If it doesn’t, then you are probably better off trying direct connection.

Security Exception: MalformedURLException: unknown protocol: socket during opening JNLP file

I have Studio.jnlp file. I tried to open it by double-click. But I found the error as below:

Summary of Exception

Details of Exception

34.5k 37 37 gold badges 147 147 silver badges 168 168 bronze badges What is the (presumably malformed) URL? Post code, error messages and stack trace; not pictures. In my case I just had to disable the proxy on. Firefox (as it is my primary browser)!

3 Answers 3

Try append «file://» to the beginning of your file path. But as Bozho proposed, you don’t need an URL here.

41.6k 17 17 gold badges 75 75 silver badges 101 101 bronze badges can anyone give me some link for using xjc through API calls?

Читайте также:  Generic types method java

This is not a valid URL. It can be made valid by prepending file:// as protocol.

But you don’t need a URL at all. You can pass a Reader (as well as an InputStream ) to the InputSource constructor. So for example:

Моя программа пытается проанализировать XML-строку, используя:

Любые предложения о том, что вызывает эту ошибку?

Обратите внимание: если вы читаете XML файл из файла, вы можете напрямую передать объект File DocumentBuilder.parse() .

В качестве побочного примечания, это шаблон, с которым вы столкнетесь много на Java. Обычно большинство API работают с Streams больше, чем с помощью Strings. Использование Streams означает, что потенциально не все содержимое должно быть загружено в память одновременно, что может быть отличной идеей!

Источник

What is a MalformedURLException and how to fix it in java?

While working with client-server programming in Java (JSE), if you are using java.net.URL class object in your program, you need to instantiate this class by passing a string representing required URL to which you need to establish connection. If the url you have passed in the string which cannot be parsed or, without legal protocol a MalformedURLException is generated.

Example

In the following Java example we are tring to get establish a connection to a page and publishing the response.

We have tampered the protocol part, changed it to htt, which should be http or, https.

import java.util.Scanner; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetExample < public static void main(String[] args) throws IOException < String url = "ht://www.tutorialspoint.com/"; URL obj = new URL(url); //Opening a connection HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //Sending the request conn.setRequestMethod("GET"); int response = conn.getResponseCode(); if (response == 200) < //Reading the response to a StringBuffer Scanner responseReader = new Scanner(conn.getInputStream()); StringBuffer buffer = new StringBuffer(); while (responseReader.hasNextLine()) < buffer.append(responseReader.nextLine()+"
"); > responseReader.close(); //Printing the Response System.out.println(buffer.toString()); > > >

Runtime Exception

Exception in thread "main" java.net.MalformedURLException: unknown protocol: htt at java.net.URL.(Unknown Source) at java.net.URL.(Unknown Source) at java.net.URL.(Unknown Source) at myPackage.HttpGetExample.main(HttpGetExample.java:11)

Handling MalformedURLException

The only Solution for this is to make sure that the url you have passed is legal, with a proper protocol.

The best way to do it is validating the URL before you proceed with your program. For validation you can use regular expression or other libraries that provide url validators. In the following program we are using exception handling itself to validate the URL.

Example

import java.util.Scanner; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; public class HttpGetExample < public static boolean isUrlValid(String url) < try < URL obj = new URL(url); obj.toURI(); return true; >catch (MalformedURLException e) < return false; >catch (URISyntaxException e) < return false; >> public static void main(String[] args) throws IOException < String url = "ht://www.tutorialspoint.com/"; if(isUrlValid(url)) < URL obj = new URL(url); //Opening a connection HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //Sending the request conn.setRequestMethod("GET"); int response = conn.getResponseCode(); if (response == 200) < //Reading the response to a StringBuffer Scanner responseReader = new Scanner(conn.getInputStream()); StringBuffer buffer = new StringBuffer(); while (responseReader.hasNextLine()) < buffer.append(responseReader.nextLine()+"
"); > responseReader.close(); //Printing the Response System.out.println(buffer.toString()); > >else < System.out.println("Enter valid URL"); >> >

Источник

Читайте также:  Фрейм во весь экран java

java.net.MalformedURLException – How to solve MalformedURLException

In this example we are going to talk about java.net.MalformedURLException . It is a subclass of IOException so it is a checked exception. What you should know is that MalformedURLException is an exception that occurs when you are trying to connect to a URL from your program but your client cannot parse the URL correctly.

1. A simple HTTP client

To demonstrate that exception, we are going to to create a simple HTTP client. This client will have on method that takes as input a URL string and returns the response, e.g the HTML code of the page that we are hitting.

package com.javacodegeeks.core.lang.NumberFormatExceptionExample; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MalformedURLExceptionExample < private static final String USER_AGENT = "Mozilla/5.0"; private static final String URL = "http://examples.javacodegeeks.com/core-java/io/bufferedreader/how-to-get-the-standard-input-in-java/"; public static void main(String[] args) < try < System.out.println(sendGetRequest(URL)); >catch (MalformedURLException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> public static String sendGetRequest(String urlString) throws IOException < URL obj = new URL(urlString); HttpURLConnection httpConnection = (HttpURLConnection) obj .openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("User-Agent", USER_AGENT); int responseCode = httpConnection.getResponseCode(); if (responseCode == 200) < BufferedReader responseReader = new BufferedReader(new InputStreamReader( httpConnection.getInputStream())); String responseLine; StringBuffer response = new StringBuffer(); while ((responseLine = responseReader.readLine()) != null) < response.append(responseLine+"\n"); >responseReader.close(); // print result return response.toString(); > return null; > >

This will output:

< html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" > 

As you can see, you get the normal HTTP response you’d expect.

Now. let’s see what happens if you change:

private static final String URL = "http://examples.javacodegeeks.com/core-java/io/bufferedreader/how-to-get-the-standard-input-in-java/";
private static final String URL = "htp://examples.javacodegeeks.com/core-java/io/bufferedreader/how-to-get-the-standard-input-in-java/";

I’ve changed http to htp . Let’s see what happens now:

java.net.MalformedURLException: unknown protocol: htp at java.net.URL.(URL.java:592) at java.net.URL.(URL.java:482) at java.net.URL.(URL.java:431) at com.javacodegeeks.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.sendGetRequest(MalformedURLExceptionExample.java:28) at com.javacodegeeks.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.main(MalformedURLExceptionExample.java:17)

So as you can see the message that accompanies that exception is pretty informative of the cause of the problem.

In general, any URL that doesn’t follow the URL Specification cannot be parsed by this client and it will complain with a MalformedURLException .

2. How to solve MalformedURLException

In general, the message that follows the exception is usually very informative of what has gone wrong. In the previous example we’ve read unknown protocol: htp , so that means that something was wrong with the protocol we’ve chosen. Usually, it is best to log the string that you give as input to any method that might throw a MalformedURLException . That way you can be sure that the method get’s the intended input correctly. Don’t forget to read the URL Specification and make sure the URL you are providing is valid. Of course input validation, like we’ve shown in java.lang.NumberFormatException – How to solve NumberFormatException with regular expressions or any kind of input validation, is a must for very sensitive applications.

Download Source Code

This was an example on java.net.MalformedURLException and how to solve MalformedURLException . You can download the source code of this example here : MalformedURLExceptionExample.zip

Источник

Оцените статью