Как исправить URIException о недопустимом символе в запросе - PullRequest
0 голосов
/ 27 июня 2019

Я использую пакет java.net для загрузки XML-файла из веб-службы, но я получаю эту ошибку: «Недопустимый символ в запросе с индексом 103: http: // ............... / current? path = // Контроллер / Компоненты / Path / DataItems / DataItem [@ type ="PART_COUNT"]

Я искал позицию.должно быть "=".

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Builder;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;


public class App 
{
    public static void main( String[] args )
    {


        HttpClient client = HttpClient
                .newBuilder()
                .version(Version.HTTP_2)
                .build();

        Builder builder;
        try {
            builder = (Builder) HttpRequest.newBuilder(new URI("http://............./current?path=//Controller/Components/Path/DataItems/DataItem[@type=\"PART_COUNT\"]"));
            HttpRequest request = ((java.net.http.HttpRequest.Builder) builder).GET().build();


            HttpResponse httpResponse = client.send(request, BodyHandlers.ofString());
             String body = (String) httpResponse.body();
             System.out.println(body);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }
}

Я ожидаю загрузки информации с URL-адреса в XML-файл. Теперь я собираюсь напечатать на экране.

<url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.7.0</version>
      <configuration>
        <source>9</source>
        <target>9</target>
        <compilerArgument>--add-modules=jdk.incubator.httpclient</compilerArgument>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.20.1</version>
      <configuration>
      <argLine>--add-modules=jdk.incubator.httpclient</argLine>
      </configuration>
    </plugin>
  </plugins>
</build>

Ответы [ 2 ]

2 голосов
/ 27 июня 2019

попытаться кодировать значение параметра запроса

//Controller/Components/Path/DataItems/DataItem[@type=\"PART_COUNT\"]

и передать закодированное значение

%2F%2FController%2FComponents%2FPath%2FDataItems%2FDataItem%5B%40type%3D%5C%22PART_COUNT%5C%22%5D

https://docs.oracle.com/javase/8/docs/api/index.html?java/net/URLEncoder.html

1 голос
/ 27 июня 2019

Я решил свою проблему. Я использовал неправильную версию Java, потому что клиентская библиотека HTTP была представлена ​​в Java 11. Я создал новый проект с Java 11. Ниже я покажу правильный код для всех. Я надеюсь, что это будет полезно.

public class HttpTest {
public static void main(String[] args) {
        HttpClient client = HttpClient
                .newBuilder()
                .version(Version.HTTP_2)
                .build();

        String query ="//Controller/Components/Path/DataItems/DataItem[@type=\"PART_COUNT\"]";
        String encodedQuery = encodeValue(query);
        System.out.println(encodedQuery);
        System.out.println();
        java.net.http.HttpRequest.Builder builder;



        try {
            builder = HttpRequest.newBuilder(new URI("http://.........../current?path="+encodedQuery));
            HttpRequest request =  builder.GET().build();

                HttpResponse httpResponse = client.send(request, BodyHandlers.ofString());
             String body = (String) httpResponse.body();
             System.out.println(body);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }

    private static String encodeValue(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getCause());
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...