retrofit2.converter.jackson.JacksonConverterFactory Java Examples

The following examples show how to use retrofit2.converter.jackson.JacksonConverterFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpUtil.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 返回retrofit的实体对象
 * @param readTimeout
 * @param writeTimeout
 * @param connectTimeout
 * @return
 */
public static Retrofit getRetrofit(String type, String requestUrl, int readTimeout, int writeTimeout, int connectTimeout){
    Converter.Factory factory = null;
    if (type.equals("String")){
        factory = ScalarsConverterFactory.create();
    }else if (type.equals("bean")){
        factory = JacksonConverterFactory.create();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(requestUrl)
            .client(HttpUtil.getOkHttpClient(type,readTimeout,writeTimeout,connectTimeout))
            .addConverterFactory(factory)//retrofit已经把Json解析封装在内部了 你需要传入你想要的解析工具就行了
            .build();
    return retrofit;
}
 
Example #2
Source File: ClientAPI.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private ClientAPI(OAuth2ClientAuthenticationInterceptor basicAuthentication) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.addInterceptor(logging);
    client.addInterceptor(new ErrorInterceptor());
    client.addInterceptor(new BearerTokenHeaderInterceptor());

    if (basicAuthentication != null) {
        client.addInterceptor(basicAuthentication);
    }

    retrofit = new Retrofit.Builder()
            .baseUrl("http://" + BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .client(client.build())
            .build();
}
 
Example #3
Source File: ClientAPI.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private ClientAPI(OAuth2ClientAuthenticationInterceptor clientAuthentication) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.addInterceptor(logging);
    client.addInterceptor(new ErrorInterceptor());
    client.addInterceptor(new BearerTokenHeaderInterceptor());

    if (clientAuthentication != null) {
        client.addInterceptor(clientAuthentication);
    }

    retrofit = new Retrofit.Builder()
            .baseUrl("http://" + BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .client(client.build())
            .build();
}
 
Example #4
Source File: ClientAPI.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private ClientAPI() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.addInterceptor(logging);
    client.addInterceptor(new BearerTokenHeaderInterceptor());
    client.addInterceptor(new ErrorInterceptor());

    retrofit = new Retrofit.Builder()
            .baseUrl("http://" + BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .client(client.build())
            .build();

}
 
Example #5
Source File: RetrofitClient.java    From BaseProject with Apache License 2.0 6 votes vote down vote up
private RetrofitClient() {
        if (mRetrofit == null) {
            ObjectMapper objectMapper = new ObjectMapper();
            //屏蔽因为Json字符串中或者Java对象中不认识的属性而导致解析失败
            objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            //modified here by fee 2016-10-19:修改成使用Builder构建者模式来构建或者重新构建Retrofit对象
//            mRetrofit = new Retrofit.Builder()
//                    .baseUrl(HOST_BASE_URL)
//                    .addConverterFactory(new JsonConverterFactory())
//
////                    .addConverterFactory(GsonConverterFactory.create())
//                    .addConverterFactory(JacksonConverterFactory.create(objectMapper))
//                    .build();
            retrofitBuilder = new Retrofit.Builder();
            retrofitBuilder.baseUrl(HOST_BASE_URL)
                    .addConverterFactory(new JsonConverterFactory())

//                    .addConverterFactory(GsonConverterFactory.create())
                    .addConverterFactory(JacksonConverterFactory.create(objectMapper));
            mRetrofit = retrofitBuilder.build();
        }
    }
 
Example #6
Source File: ClientAPI.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private ClientAPI() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.addInterceptor(logging);
    client.addInterceptor(new ErrorInterceptor());
    client.addInterceptor(new BearerTokenHeaderInterceptor());

    retrofit = new Retrofit.Builder()
            .baseUrl("http://" + BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .client(client.build())
            .build();

}
 
Example #7
Source File: IpApi.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
static IpApi create(boolean isDebug) {
  OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(new LogInterceptor());
  String url;
  if (isDebug) {
    url = BuildConfig.DEV_BACKEND_BASE_HOST;
  } else {
    url = BuildConfig.PROD_BACKEND_BASE_HOST;
  }
  Retrofit retrofit = new Retrofit.Builder().addConverterFactory(JacksonConverterFactory.create())
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
      .client(builder.build())
      .baseUrl(url)
      .build();

  return retrofit.create(IpApi.class);
}
 
Example #8
Source File: PoAManager.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
private static CampaignRepository.Api createApi(boolean isDebug) {
  OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(new LogInterceptor());
  String url;
  if (isDebug) {
    url = BuildConfig.DEV_BACKEND_BASE_HOST;
  } else {
    url = BuildConfig.PROD_BACKEND_BASE_HOST;
  }
  OkHttpClient client = builder.build();
  Retrofit retrofit =
      new Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())
          .addConverterFactory(JacksonConverterFactory.create(new ObjectMapper()))
          .client(client)
          .baseUrl(url)
          .build();

  return retrofit.create(CampaignRepository.Api.class);
}
 
Example #9
Source File: UpstreamSimpleBenchmark.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected SimpleBenchmarkClient newClient() throws Exception {
    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
    final OkHttpClient client = new OkHttpClient.Builder()
            .sslSocketFactory(context.getSocketFactory(),
                              (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0])
            .hostnameVerifier((s, session) -> true)
            .build();

    return new Retrofit.Builder()
            .baseUrl(baseUrl())
            .client(client)
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
            .create(SimpleBenchmarkClient.class);
}
 
Example #10
Source File: AppCoinsAddressProxyBuilder.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
private RemoteRepository.Api provideApi(int chainId) {
  String baseHost;
  switch (chainId) {
    case 3:
      baseHost = BuildConfig.ROPSTEN_NETWORK_BACKEND_BASE_HOST;
      break;
    default:
      baseHost = BuildConfig.MAIN_NETWORK_BACKEND_BASE_HOST;
      break;
  }
  return new Retrofit.Builder().baseUrl(baseHost)
      .client(new OkHttpClient.Builder().build())
      .addConverterFactory(JacksonConverterFactory.create())
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
      .build()
      .create(RemoteRepository.Api.class);
}
 
Example #11
Source File: ArmeriaCallFactoryLargeStreamTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30 * 1000L)
public void largeStream() throws Exception {
    final WebClient webClient =
            WebClient.builder(server.httpUri())
                     .maxResponseLength(Long.MAX_VALUE)
                     .responseTimeout(Duration.ofSeconds(30))
                     .build();
    final Service downloadService =
            ArmeriaRetrofit.builder(webClient)
                           .addConverterFactory(JacksonConverterFactory.create(OBJECT_MAPPER))
                           .build()
                           .create(Service.class);

    final ResponseBody responseBody = downloadService.largeStream().get();
    try (BufferedInputStream bufferedInputStream = new BufferedInputStream(responseBody.byteStream())) {
        long sum = 0;
        int read;
        while ((read = bufferedInputStream.read(new byte[4096])) != -1) {
            sum += read;
        }
        assertThat(sum).isEqualTo(1024 * 1024 * 10L);
    }
}
 
Example #12
Source File: MainActivity.java    From android-retrofit-test-examples with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textViewQuoteOfTheDay = (TextView) findViewById(R.id.text_view_quote);
    buttonRetry = (Button) findViewById(R.id.button_retry);
    buttonRetry.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getQuoteOfTheDay();
        }
    });

    OkHttpClient client = new OkHttpClient();
    // client.interceptors().add(new LoggingInterceptor());
    retrofit = new Retrofit.Builder()
            .baseUrl(QuoteOfTheDayConstants.BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .client(client)
            .build();
    service = retrofit.create(QuoteOfTheDayRestService.class);
    getQuoteOfTheDay();

}
 
Example #13
Source File: ManageAudienceClientFactory.java    From line-bot-sdk-java with Apache License 2.0 6 votes vote down vote up
public static ManageAudienceClient create(IntegrationTestSettings settings) {
    ObjectMapper objectMapper = ModelObjectMapper
            .createNewObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                       settings.isFailOnUnknownProperties());

    Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
            .addConverterFactory(JacksonConverterFactory.create(objectMapper));

    return ManageAudienceClient
            .builder()
            .channelToken(settings.getToken())
            .apiEndPoint(URI.create(settings.getEndpoint()))
            .retrofitBuilder(retrofitBuilder)
            .build();
}
 
Example #14
Source File: WebService.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public static Converter.Factory getDefaultConverter() {
  if (defaultConverterFactory == null) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    objectMapper.setDateFormat(df);
    defaultConverterFactory = JacksonConverterFactory.create(objectMapper);
  }
  return defaultConverterFactory;
}
 
Example #15
Source File: Front50PluginsConfiguration.java    From kork with Apache License 2.0 6 votes vote down vote up
@Bean
public static Front50Service pluginFront50Service(
    Environment environment,
    PluginOkHttpClientProvider pluginsOkHttpClientProvider,
    Map<String, PluginRepositoryProperties> pluginRepositoriesConfig) {
  PluginRepositoryProperties front50RepositoryProps =
      pluginRepositoriesConfig.get(PluginsConfigurationProperties.FRONT5O_REPOSITORY);

  URL front50Url = getFront50Url(environment, front50RepositoryProps);

  ObjectMapper objectMapper =
      new ObjectMapper()
          .registerModule(new KotlinModule())
          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          .configure(SerializationFeature.INDENT_OUTPUT, true)
          .setSerializationInclusion(JsonInclude.Include.NON_NULL);

  return new Retrofit.Builder()
      .addConverterFactory(JacksonConverterFactory.create(objectMapper))
      .baseUrl(front50Url)
      .client(pluginsOkHttpClientProvider.getOkHttpClient())
      .build()
      .create(Front50Service.class);
}
 
Example #16
Source File: HttpUtil.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 返回retrofit的实体对象
 * @param readTimeout
 * @param writeTimeout
 * @param connectTimeout
 * @return
 */
public static Retrofit getRetrofit(String type, String requestUrl, int readTimeout, int writeTimeout, int connectTimeout){
    Converter.Factory factory = null;
    if (type.equals("String")){
        factory = ScalarsConverterFactory.create();
    }else if (type.equals("bean")){
        factory = JacksonConverterFactory.create();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(requestUrl)
            .client(HttpUtil.getOkHttpClient(type,readTimeout,writeTimeout,connectTimeout))
            .addConverterFactory(factory)//retrofit已经把Json解析封装在内部了 你需要传入你想要的解析工具就行了
            .build();
    return retrofit;
}
 
Example #17
Source File: OkHttpRibbonInterceptorTests.java    From spring-cloud-square with Apache License 2.0 5 votes vote down vote up
@Bean
public TestAppClient testAppClient(@LoadBalanced OkHttpClient.Builder builder) {
	Retrofit retrofit = new Retrofit.Builder()
			// here you use a service id, or virtual hostname
			// rather than an actual host:port, ribbon will
			// resolve it
			.baseUrl("http://testapp")
			.client(builder.build())
			.addConverterFactory(JacksonConverterFactory.create())
			.build();
	return retrofit.create(TestAppClient.class);
}
 
Example #18
Source File: YelpAPIFactory.java    From yelp-android with MIT License 5 votes vote down vote up
/**
 * Initiate a {@link YelpAPI} instance.
 *
 * @return an instance of {@link YelpAPI}.
 */
public YelpAPI createAPI() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(getAPIBaseUrl())
            .addConverterFactory(JacksonConverterFactory.create())
            .client(this.httpClient)
            .build();

    return retrofit.create(YelpAPI.class);
}
 
Example #19
Source File: OkHttpLoadBalancerInterceptorTests.java    From spring-cloud-square with Apache License 2.0 5 votes vote down vote up
@Bean
public TestAppClient testAppClient(@LoadBalanced OkHttpClient.Builder builder) {
	Retrofit retrofit = new Retrofit.Builder()
			// here you use a service id, or virtual hostname
			// rather than an actual host:port, ribbon will
			// resolve it
			.baseUrl("http://testapp")
			.client(builder.build())
			.addConverterFactory(JacksonConverterFactory.create())
			.build();
	return retrofit.create(TestAppClient.class);
}
 
Example #20
Source File: PafClientConfig.java    From vics with MIT License 5 votes vote down vote up
@Bean
public Retrofit retrofit(OkHttpClient client, ObjectMapper objectMapper, AppProperties appProperties) {
    return new Retrofit.Builder()
            .addConverterFactory(JacksonConverterFactory.create(objectMapper))
            .baseUrl(appProperties.getPafApiBaseUrl())
            .client(client)
            .build();
}
 
Example #21
Source File: RetrofitFactory.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Retrofit fromServerUrl(String serverUrl) {
    return new Retrofit.Builder()
            .baseUrl(serverUrl)
            .addConverterFactory(JacksonConverterFactory.create(new ObjectMapper()))
            .addConverterFactory(FilterConverterFactory.create())
            .addConverterFactory(FieldsConverterFactory.create())
            .build();
}
 
Example #22
Source File: OTwilioInitModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public ITwilioService provideTwilioHttpService(@Named("twilio.url") String twilioUrl) {
  return new Retrofit.Builder()
          .baseUrl(twilioUrl)
          .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
          .addConverterFactory(JacksonConverterFactory.create())
          .build()
          .create(ITwilioService.class);
}
 
Example #23
Source File: ClueCommandClient.java    From clue with Apache License 2.0 5 votes vote down vote up
public ClueCommandClient(URL url) throws Exception {
    final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    if ("https".equals(url.getProtocol())) {
        try {
            setSslSocketFactory(okHttpClientBuilder);
        } catch(Exception e) {
            throw new IllegalStateException("cannot create ssl connection: " + e);
        }
    }

    final OkHttpClient okHttpClient = okHttpClientBuilder.readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .build();

    Retrofit restAdator = new Retrofit.Builder().baseUrl(HttpUrl.get(url))
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create(mapper))
            .client(okHttpClient).build();

    svc = restAdator.create(ClueCommandService.class);

    cmdlineHelper = new CmdlineHelper(new Supplier<Collection<String>>() {
        @Override
        public Collection<String> get() {
            try {
                return getCommands();
            } catch (Exception e) {
                System.out.println("unable obtaining command list");
                return Collections.emptyList();
            }
        }
    }, null);
}
 
Example #24
Source File: QuoteOfTheDayMockAdapterTest.java    From android-retrofit-test-examples with MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    retrofit = new Retrofit.Builder().baseUrl("http://test.com")
            .client(new OkHttpClient())
            .addConverterFactory(JacksonConverterFactory.create())
            .build();

    NetworkBehavior behavior = NetworkBehavior.create();

    mockRetrofit = new MockRetrofit.Builder(retrofit)
            .networkBehavior(behavior)
            .build();
}
 
Example #25
Source File: ServiceRest.java    From RxZhihuDaily with MIT License 5 votes vote down vote up
private ServiceApi cachedService(){
    if(cachedServiceApi == null){
        Retrofit retrofit = new Retrofit.Builder()
                .client(createCachedClient())
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        cachedServiceApi = retrofit.create(ServiceApi.class);
    }
    return cachedServiceApi;
}
 
Example #26
Source File: ServiceRest.java    From RxZhihuDaily with MIT License 5 votes vote down vote up
private ServiceApi rtcService(){
    if(rtcServiceApi == null){
        Retrofit retrofit = new Retrofit.Builder()
                .client(createRtcClient())
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        rtcServiceApi = retrofit.create(ServiceApi.class);
    }

    return rtcServiceApi;
}
 
Example #27
Source File: BeaconControlManagerImpl.java    From BeaconControl_Android_SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Retrofit getRetrofitInstance(String serviceBaseUrl, ObjectMapper objectMapper, OkHttpClient okHttpClient) {
    return new Retrofit.Builder()
            .baseUrl(serviceBaseUrl)
            .client(okHttpClient)
            .addConverterFactory(JacksonConverterFactory.create(objectMapper))
            .build();
}
 
Example #28
Source File: LineMessagingClientFactory.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
public static LineMessagingClient create(IntegrationTestSettings settings) {
    ObjectMapper objectMapper = ModelObjectMapper
            .createNewObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                       settings.isFailOnUnknownProperties());

    Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
            .addConverterFactory(JacksonConverterFactory.create(objectMapper));

    return LineMessagingClient
            .builder(settings.getToken())
            .apiEndPoint(URI.create(settings.getEndpoint()))
            .retrofitBuilder(retrofitBuilder)
            .build();
}
 
Example #29
Source File: MapsClientConfig.java    From vics with MIT License 5 votes vote down vote up
@Bean
public MapsClient mapsClient(AppProperties appProperties, ObjectMapper objectMapper) {
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(chain -> {
        Request request = chain.request().newBuilder().addHeader("X-Authorization", appProperties.getAddressLookupToken()).build();
        return chain.proceed(request);
    }).build();

    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(JacksonConverterFactory.create(objectMapper))
            .baseUrl(appProperties.getAddressLookupBaseUrl())
            .client(client)
            .build();

    return retrofit.create(MapsClient.class);
}
 
Example #30
Source File: ModuleRest.java    From AndroidStarter with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public GitHubService provideGithubService(@NonNull final OkHttpClient poOkHttpClient) {
    final Retrofit loRetrofit = new Retrofit.Builder()
            .baseUrl("https://api.github.com")
            .client(poOkHttpClient)
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
    return loRetrofit.create(GitHubService.class);
}