Форум программистов, компьютерный форум, киберфорум
Java EE (J2EE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/9: Рейтинг темы: голосов - 9, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23

Retrofit2, передача заголовка

31.05.2019, 15:47. Показов 2105. Ответов 18

Студворк — интернет-сервис помощи студентам
Доброе время суток,

В проекте на Java Spring.
Есть класс для веб сервиса.
Для вызова методов используется Retrofit.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
        try {
          retrofit = new Retrofit.Builder()
                .baseUrl(get("host")+"/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
 
            intf = retrofit.create(Link.class);
        }catch(Exception e){
            s_error="End Retrofit error "+ e.toString();
            logger.error(s_error);
            return s_error;
        }
 
        
        try {
            Call<Map<String, Object>> call = intf.executeMethodMp("auth?check_core_auths",params1);
            retrofit2.Response<Map<String, Object>> response = call.execute();
            
            ....
Теперь появилась необходимость передать headers.
Добавил такой код:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("Accept", "application/pyur.v1")
                        .header("Authorization", "xzczxcsdadasd")
                        .header("Content-Type", "application/json")
                        .method(original.method(),original.body())
                        .build();
                return chain.proceed(request);
            }
        }).build();
Теперь при запуске сервера такая ошибка:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
SEVERE [localhost-startStop-1] com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized WSSERVLET11: failed to parse runtime descriptor: java.lang.NoClassDefFoundError: retrofit2/Converter$Factory
 java.lang.NoClassDefFoundError: retrofit2/Converter$Factory
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.getImplementorClass(DeploymentDescriptorParser.java:545)
    at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:223)
    at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:147)
    at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:108)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4770)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:624)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1833)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: retrofit2.Converter$Factory
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1364)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1185)
    ... 19 more
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
31.05.2019, 15:47
Ответы с готовыми решениями:

Передача заголовка @header
Здравствуйте! Можно ли изменить заголовок? Например, есть: @header('Location:http://site.com/index.php?login=admin&amp;pass=123');...

Передача заголовка из PHP кода
Доброго времен суток. в html коде перед загрузкой страницы посылается заголовок. в котором содержится кодировка. &lt;head&gt; ...

Передача заголовка товара в форму php
Добрый день, есть магазин на woocommere, заказчик хочет что бы в каталоге товаров, в карточке с товаром была кнопка купить, при нажатие на...

18
 Аватар для reisal78
944 / 687 / 230
Регистрация: 28.04.2013
Сообщений: 1,925
01.06.2019, 11:20
Цитата Сообщение от GabitJunior Посмотреть сообщение
В проекте на Java Spring.
Цитата Сообщение от GabitJunior Посмотреть сообщение
Для вызова методов используется Retrofit.
Помоему в спринге RestTemplate есть или как-то так...

А по сабжу... скорее всего зависимости для ретрофита не хватает, покажите какие у вас подключены
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
01.06.2019, 16:48  [ТС]
Файлы прикрепил.
Вложения
Тип файла: 7z Gabit_Example.7z (5.6 Кб, 4 просмотров)
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
01.06.2019, 17:42
какая каша в зависимостях
0
 Аватар для reisal78
944 / 687 / 230
Регистрация: 28.04.2013
Сообщений: 1,925
01.06.2019, 19:17
GabitJunior,

Вам следует навести порядок в dependency как минимум избавится от разных версий ретрофита

минимум для работы retrofit:

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
            <dependency>
                <groupId>com.squareup.retrofit2</groupId>
                <artifactId>retrofit</artifactId>
                <version>${retrofit.version}</version>
            </dependency>
<!--
            <dependency>
                <groupId>com.squareup.retrofit2</groupId>
                <artifactId>adapter-rxjava2</artifactId>
                <version>${retrofit.version}</version>
            </dependency>
-->
            <dependency>
                <groupId>com.squareup.retrofit2</groupId>
                <artifactId>converter-gson</artifactId>
                <version>${retrofit.version}</version>
            </dependency>
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
02.06.2019, 14:34  [ТС]
reisal78,
Почистил build.gradle как Вы написали, теперь он выглядит так:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "info.solidsoft.gradle.pitest:gradle-pitest-plugin:1.1.6"
    }
}
 
plugins {
    id "org.sonarqube" version "1.1"
}
 
defaultTasks "build"
 
apply plugin: "java"
apply plugin: "war"
apply plugin: "findbugs"
apply plugin: "eclipse"
apply plugin: "idea"
apply plugin: "info.solidsoft.pitest"
 
compileJava {
    //enable compilation in a separate daemon process
    options.fork = true
    //enable incremental compilation
    options.incremental = true
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}
 
configurations {
    tomcatAnt
//    agent
    sshAntTask
    providedCompile {
        exclude group: "org.slf4j", module: "slf4j-simple"
        exclude group: "org.slf4j", module: "slf4j-log4j12"
    }
}
 
repositories {
    mavenCentral()
    flatDir {
        dirs "lib"
    }
}
 
ext {
    springVersion = "4.3.13.RELEASE"
    //springVersion = "5.1.3.RELEASE"
    springSecurityVersion = "4.0.4.RELEASE"
    //springSecurityVersion = "5.1.2.RELEASE"
    springSessionVersion = "1.1.0.RELEASE"
    //springSessionVersion = "1.3.4.RELEASE"
}
 
dependencies {
    providedCompile fileTree(dir: "lib", include: ["*.jar"])
    providedCompile "javax.servlet:javax.servlet-api:3.1.0"
    providedCompile "org.springframework:spring-context:$springVersion"
    providedCompile "org.springframework:spring-jdbc:$springVersion"
    providedCompile "org.springframework:spring-tx:$springVersion"
    providedCompile "org.springframework:spring-webmvc:$springVersion"
    providedCompile "org.springframework:spring-websocket:$springVersion"
    providedCompile "org.springframework:spring-messaging:$springVersion"
    providedCompile "org.springframework.security:spring-security-config:$springSecurityVersion"
    providedCompile "org.springframework.security:spring-security-web:$springSecurityVersion"
    providedCompile "org.springframework.security:spring-security-messaging:$springSecurityVersion"
    providedCompile "org.springframework.session:spring-session:$springSessionVersion"
    providedCompile "com.google.code.gson:gson:2.5"
    providedCompile "net.lingala.zip4j:zip4j:1.3.2"
    providedCompile "commons-codec:commons-codec:1.10"
    providedCompile "commons-validator:commons-validator:1.5.0"
    providedCompile "org.apache.santuario:xmlsec:1.4.4"
    providedCompile "commons-logging:commons-logging:1.1.1"
    providedCompile "org.elasticsearch:elasticsearch:1.7.5"
    providedCompile "org.postgresql:postgresql:42.2.5"
    providedCompile "org.apache.commons:commons-lang3:3.4"
    providedCompile "org.apache.tika:tika-core:1.11"
    providedCompile "org.apache.poi:poi:3.12"
    providedCompile "org.apache.poi:poi-ooxml:3.12"
    providedCompile "org.apache.poi:ooxml-schemas:1.1"
    providedCompile "com.sun.mail:mailapi:1.5.2"
    providedCompile "com.sun.mail:smtp:1.5.2"
    providedCompile "org.slf4j:slf4j-api:1.7.13"
    providedCompile "org.slf4j:jcl-over-slf4j:1.7.13"
    providedCompile "org.slf4j:log4j-over-slf4j:1.7.13"
    providedCompile "ch.qos.logback:logback-classic:1.1.3"
    providedCompile "ch.qos.logback:logback-core:1.1.3"
    providedCompile "org.fusesource.jansi:jansi:1.8"
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
    compile group: 'com.sun.xml.ws', name: 'jaxws-rt', version: '2.1.3'
    compile 'commons-fileupload:commons-fileupload:1.2.2'
    compile 'commons-io:commons-io:2.6'
 
    compile group: 'com.fasterxml', name: 'jackson-xml-databind', version: '0.6.2'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.0.1'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.2.1'
    compile group: 'com.amazonaws', name: 'aws-java-sdk-cloudfront', version: '1.11.455'
    compile group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.11.541'
 
    compile group: 'com.squareup.retrofit2', name: 'retrofit', version: '2.3.0'
    compile group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.3.0'
 
    compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.10.0'
    compile group: 'com.squareup.okhttp3', name: 'logging-interceptor', version: '3.9.1'
 
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'
 
    testCompile "junit:junit:4.+"
    testCompile "org.hamcrest:hamcrest-all:1.3"
    testCompile "org.springframework:spring-test:$springVersion"
    testCompile "org.mockito:mockito-core:2.0.32-beta"
    testCompile "com.google.code.findbugs:findbugs:3.0.1"
    tomcatAnt "org.apache.tomcat:tomcat-catalina-ant:8.0.26"
    sshAntTask "org.apache.ant:ant-jsch:1.9.6"
}
 
war {
    baseName = "auction"
}
 
findbugsMain {
    reports {
        xml.enabled = false
        html.enabled = true
    }
}
 
findbugsTest {
    reports {
        xml.enabled = false
        html.enabled = true
    }
}
 
findbugs {
    ignoreFailures = false
    excludeFilter = file("conf/findbugs_filters.xml")
}
 
pitest {
    pitestVersion = "1.1.9"
    targetClasses = ["com.bas.auction.*"]  //by default "${project.group}.*"
    threads = 4
    excludedMethods = ["hashCode", "equals", "getSqlPath", "getEntityType"]
    excludedClasses = ["com.bas.auction.*.dto.*"]
    excludedGroups = ["com.bas.auction.test.IntegrationTests"]
    outputFormats = ["HTML"]
    jvmArgs = ["-Xmx1024m"]
}
 
sonarqube {
    properties {
        property "sonar.projectKey", "auction"
        property "sonar.projectName", "auction"
        property "sonar.projectVersion", "1.0"
        property "sonar.sourceEncoding", "UTF-8"
    }
}
 
eclipse {
    classpath {
        //you can tweak the classpath of the Eclipse project by adding extra configurations:
        plusConfigurations = [ configurations.compile, configurations.runtime, configurations.testCompile ]
        //default settings for downloading sources and Javadoc:
        downloadSources = true
        downloadJavadoc = false
    }
}
 
test {
    useJUnit {
        excludeCategories "com.bas.auction.test.IntegrationTests"
    }
}
 
 
tasks.eclipse.dependsOn(cleanEclipse)
tasks.idea.dependsOn(cleanIdea)
 
task wrapper(type: Wrapper) {
    gradleVersion = "2.11"
}
 
task copyToLib(type: Copy, description: "Copies all runtime dependency jars to runtimeLibs dir") {
    into "$buildDir/runtimeLibs"
    from configurations.runtime
    exclude "javax.servlet*", "tomcat-*"
}
Потом заново перегенерировал jaxws:
Code
1
wsgen -keep -cp . com.bas.auction.core.config.webservice.core.CoreWebServiceImpl
И перекомпилировал war.
Теперь при запуске сервера пишет:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
ERROR o.s.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.LinkageError: loader constraint violation: when resolving method "org.springframework.http.converter.json.GsonHttpMessageConverter.setGson(Lcom/google/gson/Gson;)V" the class loader (instance of org/apache/catalina/loader/ParallelWebappClassLoader) of the current class, com/bas/auction/core/config/WebMvcConfig, and the class loader (instance of java/net/URLClassLoader) for the method's defining class, org/springframework/http/converter/json/GsonHttpMessageConverter, have different Class objects for the type com/google/gson/Gson used in the signature
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:171) [spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at javax.servlet.GenericServlet.init(GenericServlet.java:158) [servlet-api.jar:3.1.FR]
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1142) [catalina.jar:8.5.40]
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:986) [catalina.jar:8.5.40]
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4956) [catalina.jar:8.5.40]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5270) [catalina.jar:8.5.40]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.5.40]
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754) [catalina.jar:8.5.40]
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730) [catalina.jar:8.5.40]
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734) [catalina.jar:8.5.40]
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:624) [catalina.jar:8.5.40]
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1833) [catalina.jar:8.5.40]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_212]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_212]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_212]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.LinkageError: loader constraint violation: when resolving method "org.springframework.http.converter.json.GsonHttpMessageConverter.setGson(Lcom/google/gson/Gson;)V" the class loader (instance of org/apache/catalina/loader/ParallelWebappClassLoader) of the current class, com/bas/auction/core/config/WebMvcConfig, and the class loader (instance of java/net/URLClassLoader) for the method's defining class, org/springframework/http/converter/json/GsonHttpMessageConverter, have different Class objects for the type com/google/gson/Gson used in the signature
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 31 common frames omitted
Caused by: java.lang.LinkageError: loader constraint violation: when resolving method "org.springframework.http.converter.json.GsonHttpMessageConverter.setGson(Lcom/google/gson/Gson;)V" the class loader (instance of org/apache/catalina/loader/ParallelWebappClassLoader) of the current class, com/bas/auction/core/config/WebMvcConfig, and the class loader (instance of java/net/URLClassLoader) for the method's defining class, org/springframework/http/converter/json/GsonHttpMessageConverter, have different Class objects for the type com/google/gson/Gson used in the signature
    at com.bas.auction.core.config.WebMvcConfig.configureMessageConverters(WebMvcConfig.java:30) ~[classes/:na]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurerComposite.configureMessageConverters(WebMvcConfigurerComposite.java:136) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration.configureMessageConverters(DelegatingWebMvcConfiguration.java:117) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.getMessageConverters(WebMvcConfigurationSupport.java:718) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerAdapter(WebMvcConfigurationSupport.java:529) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$86d8e56d.CGLIB$requestMappingHandlerAdapter$35(<generated>) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$86d8e56d$$FastClassBySpringCGLIB$$3626e7d8.invoke(<generated>) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$86d8e56d.requestMappingHandlerAdapter(<generated>) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_212]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_212]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_212]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 32 common frames omitted
02-Jun-2019 12:51:18.998 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDescriptor Deployment of configuration descriptor [/opt/tomcat/conf/Catalina/localhost/ROOT.xml] has finished in [14,115] ms
Добавлено через 32 минуты
Попробовал обновить версию до 2.5:
Code
1
2
compile group: 'com.squareup.retrofit2', name: 'retrofit', version: '2.3.0'
    compile group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.3.0'
Результат тот же:
Code
1
2
3
4
5
6
7
8
9
10
ERROR o.s.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' 
defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' 
threw exception; nested exception is java.lang.LinkageError: loader constraint violation: 
when resolving method "org.springframework.http.converter.json.GsonHttpMessageConverter.setGson(Lcom/google/gson/Gson;)V" 
the class loader (instance of org/apache/catalina/loader/ParallelWebappClassLoader) of the current class, com/bas/auction/core/config/WebMvcConfig, 
and the class loader (instance of java/net/URLClassLoader) for the method's defining class, 
org/springframework/http/converter/json/GsonHttpMessageConverter, have different Class objects for the type com/google/gson/Gson used in the signature
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
02.06.2019, 16:33
ну смотри, откуда у тебя gson прилетает, наверняка с версиями по прежнему косяк
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
02.06.2019, 21:02  [ТС]
xoraxax,
Он из retrofit вызывается.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.bas.auction.core.config.webservice.core;
 
import okhttp3.*;
import retrofit2.Call;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Retrofit;
 
...
 
 
        try {
          retrofit = new Retrofit.Builder()
                .baseUrl(get("host")+"/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
 
            intf = retrofit.create(Link.class);
        }catch(Exception e){
            s_error="End Retrofit error "+ e.toString();
            logger.error(s_error);
            return s_error;
        }
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
03.06.2019, 00:09
зависимости смотри какая разница откуда вызывается
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
03.06.2019, 01:20  [ТС]
xoraxax,
Убрал зависимость google.gson.
Теперь с gson связанная только эти зависимости:
Java
1
2
    compile group: 'com.squareup.retrofit2', name: 'retrofit', version: '2.5.0'
    compile group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.5.0'
Какую с какой сравнить ?
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
03.06.2019, 09:08
поищи команду, которая показывает дерево зависимостей, возможно gradle dependencies, смотри, чтобы не было разных версий gson
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
03.06.2019, 12:32  [ТС]
Использую Idea 15.0.6,
Вложил анализатор зависимостей.
Это он ?
Миниатюры
Retrofit2, передача заголовка  
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
03.06.2019, 13:18  [ТС]
вот так набрал в командной строке:
Code
1
./gradlew dependencies
Файл прилагается.
Вложения
Тип файла: 7z dependencies.7z (2.8 Кб, 0 просмотров)
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
03.06.2019, 13:20  [ТС]
Где есть gson, только вот эти строки:
Code
1
2
3
4
5
6
7
+--- com.google.code.gson:gson:2.8.2
+--- com.squareup.retrofit2:retrofit:2.5.0
|    \--- com.squareup.okhttp3:okhttp:3.12.0
|         \--- com.squareup.okio:okio:1.15.0
+--- com.squareup.retrofit2:converter-gson:2.5.0
|    +--- com.squareup.retrofit2:retrofit:2.5.0 (*)
|    \--- com.google.code.gson:gson:2.8.2
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
03.06.2019, 13:39
Цитата Сообщение от GabitJunior Посмотреть сообщение
com/bas/auction/core/config/WebMvcConfig,
and the class loader (instance of java/net/URLClassLoader) for the method's defining class,
org/springframework/http/converter/json/GsonHttpMessageConverter, have different Class objects for the type com/google/gson/Gson used in the signature
короче разбирайся с этим
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
03.06.2019, 14:56  [ТС]
xoraxax,
Не понятно как разобраться,
0
 Аватар для reisal78
944 / 687 / 230
Регистрация: 28.04.2013
Сообщений: 1,925
03.06.2019, 16:53
GabitJunior, приложение spring boot?
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
04.06.2019, 12:52  [ТС]
reisal78, Spring Framework.
Может у Вас есть рабочий пример ?

Я retrofit использую чтобы обращаться классам бэк-энда, т.е. основного проекта.
Сейчас Веб-сервис прикручен к нему как внешнее приложение получается (jaxws).
0
0 / 0 / 0
Регистрация: 31.05.2019
Сообщений: 23
20.06.2019, 15:21  [ТС]
Задача была решена немного другим способом.
Интерфейс (Link.java):
Кликните здесь для просмотра всего текста
Java
1
2
3
4
public interface Link {
    @POST
    Call<Map<String, String>> executeAuth(@Url String url, @Header("Content-Type") String contentRange, @Body RequestBody user);
}


Выполнение из класса Web Service:
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
            OkHttpClient client2 = new OkHttpClient();
            client2.interceptors().add(new Interceptor() {
                @Override
                public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                    return chain.proceed(chain.request()
                            .newBuilder()
                            .build());
                }
            });
            try {
                retrofit2 = new Retrofit.Builder()
                        .baseUrl(get("host")+"/")
                        .client(client2)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                intf2 = retrofit2.create(Link.class);
            }catch(Exception e){
                logger.error("End Retrofit-2 error "+ e.toString());
                return "error "+ e.toString();
            }
 
            String s_text = "данные необходимые для submit";
            RequestBody r_body = RequestBody.create(MediaType.parse("text/plain"), s_text);
            Call<Map<String, String>> call2 = intf2.executeAuth("login", "application/x-www-form-urlencoded", r_body);
 
            Response<Map<String, String>> response2 = call2.execute();


Возникает ошибка на последней строке:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

Какой тип задать, чтобы получить ответ ?

Добавлено через 30 минут
Вернее как сделать чтобы он пытался конвертировать, а получил ответ как строку ?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
20.06.2019, 15:21
Помогаю со студенческими работами здесь

Retrofit2, POST запрос
Пытаюсь передать данные на веб сервер. читал туториалы но не могу понять до конца как это реализовать. Создал интерфейс, подключил все...

Retrofit2. Не работает пример
Не работает пример: https://habrahabr.ru/post/314028/ https://github.com/Mikhail57/RetrofitTutorial У кого-нибудь работает?

Запрос через Retrofit2
Пытаюсь получить ответ с сайта, но кидает в метод onFailure(), вот код: package wradchuk.pointapprf2.net; public class...

Retrofit2 POST - JsonSyntaxException
Помогите с ошибкой пожалуйста: public interface ApiValidate { @Headers(&quot;Content-Type: application/json&quot;) ...

При переносе сложного заголовка таблицы в Word теряются границы ячеек заголовка
При переносе &quot;сложного&quot; заголовка таблицы в Word на следующий лист (на первом листе таблицы все границы у ячеек есть!) теряются некоторые...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
19
Ответ Создать тему
Новые блоги и статьи
Символьное дифференцирование
igorrr37 13.02.2026
/ * Логарифм записывается как: (x-2)log(x^2+2) - означает логарифм (x^2+2) по основанию (x-2). Унарный минус обозначается как ! в-строка - входное арифметическое выражение в инфиксной(обычной). . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
Установка Qt-версии Lazarus IDE в Debian Trixie Xfce
volvo 10.02.2026
В общем, достали меня глюки IDE Лазаруса, собранной с использованием набора виджетов Gtk2 (конкретно: если набирать текст в редакторе и вызвать подсказку через Ctrl+Space, то после закрытия окошка. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru