Do you know java.io.FileNotFoundException: META-INF/native/netty_tcnative_windows_x86_64.dll error in Spring WebFlux? - spring-webflux

everyone
When I try the code below,
private void request() {
HttpClient httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.resolver(DefaultAddressResolverGroup.INSTANCE)
.responseTimeout(Duration.ofSeconds(60))
.doOnConnected(connection ->
connection.addHandlerLast(new ReadTimeoutHandler(60, TimeUnit.SECONDS))
.addHandlerLast(new WriteTimeoutHandler(60, TimeUnit.SECONDS)));
WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient)).build();
String requestUrl = "https://my-url";
Mono<String> result = webClient.post()
.uri(requestUrl)
.contentType(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class);
String token = result.block();
return token;
}
This error occurred.. What should I do?
Thank you for share your knowledge.

Related

Response code: 400 Bad request/Error Message: No Ids were specified

I am trying to send Get request using RestSharp but getting this message in response:Bad Request/
{"Message":"P1001: No Ids were specified"}. Could someone help please to figure out that? Seems like it's not adding Parameter list to the Request Body...
Here is my code:
public partial class DTO
{
public List<string> evidenceIds { get; set; }
}
public RestRequest GetPlayRequest(Method requestType, string token)
{
DTO MyObject = new DTO();
MyObject.evidenceIds = new List<string>();
MyObject.evidenceIds.Add("6F00CAE1-F16E-47F6-AF3F-D10305DD7859");
string jsonString = JsonConvert.SerializeObject(MyObject);
var restRequest = new RestRequest(requestType);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddParameter("text/json", jsonString, ParameterType.RequestBody);
restRequest.AddHeader("Organization", "Bofa");
restRequest.AddHeader("Username", "Admin");
restRequest.AddParameter("Authorization", "Bearer " + token, ParameterType.HttpHeader);
return restRequest;
}
The request with all params
The Content response after sending the request
I can suggest the following:
public RestRequest GetPlayRequest(Method method, string token)
{
var obj = new DTO { evidenceIds = new string[]
{"6F00CAE1-F16E-47F6-AF3F-D10305DD7859" }
};
return new RestRequest(method)
.AddJsonBody(obj)
.AddHeader("Organization", "Bofa")
.AddHeader("Username", "Admin");
.AddHeader("Authorization", $"Bearer {token}");
}

Do we have to pass header values from WebClient in Zipkins

I am using Spring boot and following libraries in client and server,
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.SR2"
}
}
// Spring Cloud Sleuth
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-sleuth', version: '2.0.1.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-zipkin', version: '2.0.1.RELEASE'
Based upon spring documentation, "https://cloud.spring.io/spring-cloud-sleuth/"
Run this app and then hit the home page. You will see traceId and spanId populated in the logs. If this app calls out to another one (e.g. with RestTemplate) it will send the trace data in headers and if the receiver is another Sleuth app you will see the trace continue there.
How will this work with Spring5 web client?
It will work in the same way. It's enough to inject a bean of WebClient or WebClientBuilder type. Check out this sample https://github.com/spring-cloud-samples/sleuth-documentation-apps/blob/master/service1/src/main/java/io/spring/cloud/sleuth/docs/service1/Service2Client.java
/**
* #author Marcin Grzejszczak
*/
#Component
class Service2Client {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final WebClient webClient;
private final String serviceAddress;
private final Tracer tracer;
Service2Client(WebClient webClient,
#Value("${service2.address:localhost:8082}") String serviceAddress,
Tracer tracer) {
this.webClient = webClient;
this.serviceAddress = serviceAddress;
this.tracer = tracer;
}
public String start() throws InterruptedException {
log.info("Hello from service1. Setting baggage foo=>bar");
Span span = tracer.currentSpan();
String secretBaggage = ExtraFieldPropagation.get("baggage");
log.info("Super secret baggage item for key [baggage] is [{}]", secretBaggage);
if (StringUtils.hasText(secretBaggage)) {
span.annotate("secret_baggage_received");
span.tag("baggage", secretBaggage);
}
String baggageKey = "key";
String baggageValue = "foo";
ExtraFieldPropagation.set(baggageKey, baggageValue);
span.annotate("baggage_set");
span.tag(baggageKey, baggageValue);
log.info("Hello from service1. Calling service2");
String response = webClient.get()
.uri("http://" + serviceAddress + "/foo")
.exchange()
.block()
.bodyToMono(String.class).block();
Thread.sleep(100);
log.info("Got response from service2 [{}]", response);
log.info("Service1: Baggage for [key] is [" + ExtraFieldPropagation.get("key") + "]");
return response;
}
#NewSpan("first_span")
String timeout(#SpanTag("someTag") String tag) {
try {
Thread.sleep(300);
log.info("Hello from service1. Calling service2 - should end up with read timeout");
String response = webClient.get()
.uri("http://" + serviceAddress + "/readtimeout")
.retrieve()
.onStatus(httpStatus -> httpStatus.isError(), clientResponse -> {
throw new IllegalStateException("Exception!");
})
.bodyToMono(String.class)
.block();
log.info("Got response from service2 [{}]", response);
return response;
} catch (Exception e) {
log.error("Exception occurred while trying to send a request to service 2", e);
throw new RuntimeException(e);
}
}
}

Xamarin Android HttpClient Error when use from a Class

I have the following code that errors out when going to site what has SSL. (Error: SecureChannelFailure (The authentication or decryption has failed.) Their SSL cert is valid. When the HttpClient code is called directly there is not issue. What is wrong with my code?
Uri uri =new Uri("https://jsonplaceholder.typicode.com/posts/1");
using (HttpClient httpclient = new HttpClientClass())
{
var tt = await httpclient.GetAsync(uri);
string tx = await tt.Content.ReadAsStringAsync();
Log.Info(TAG, tx);
}
public class HttpClientClass : HttpClient
{
private HttpClient _httpclient = null;
private HttpClientHandler messagehandler = new Xamarin.Android.Net.AndroidClientHandler();
public HttpClientClass()
{
_httpclient = new HttpClient(messagehandler);
}
}
Code with No Problem
Uri uri =new Uri("https://jsonplaceholder.typicode.com/posts/1");
using (HttpClient httpclient = new HttpClient())
{
var tt = await httpclient.GetAsync(uri);
string tx = await tt.Content.ReadAsStringAsync();
Log.Info(TAG, tx);
}
Thanks to Https with TLS 1.2 in Xamarin
here is the solution. Add Nuget modernhttpclient by Paul Betts and use below. That should work within class or not.
Uri uri = new Uri("https://jsonplaceholder.typicode.com/posts/1");
using (var httpClient = new HttpClient(new NativeMessageHandler()))
{
var tt = await httpClient.GetAsync(uri);
string tx = await tt.Content.ReadAsStringAsync();
//Log.Info(TAG, tx);
}

Retrofit 2.0 headers authentication

private void setUpRestClient() {
OkHttpClient client = new OkHttpClient();
client.interceptors().add(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", new SharedPreferencesUtil(getBaseContext()).getToken())
.header("Content-Type", "application/json")
.method(original.method(),original.body())
.build();
return chain.proceed(request);
}
});
RestClient.getInstance().configureRestAdapter(this, getResources().getString(R.string.base_url),client);
}
public void configureRestAdapter(final Context context, String baseUrl, OkHttpClient client) {
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
service = retrofit.create(NetworkServiceInterface.class);
}
This now gives me a failure return in Retrofit 2.0, originally I had it without the "Authorization" header and it was giving me unauthorized, which is understandable. But now I'm authorizing it with my auth token and it fails. New to Retrofit 2.0, thanks --
You can pass Authorization Header as:
#GET("/v1/OrderReport.json")
Call<POJO_Class> getExampleMethod(#Header("Authorization") String token, #Query("id") String id);
and then call as:
getExampleMethod("Basic " + token, id);
You can add Authorization Header for every calls using Interceptor in Retrofit 2, by using the OkHttpClient.Builder class. Like this.
import okhttp3.OkHttpClient;
import okhttp3.Interceptor;
OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
//getAccessToken is your own accessToken(retrieve it by saving in shared preference or any other option )
if(getAccessToken().isEmpty()){
PrintLog.error("retrofit 2","Authorization header is already present or token is empty....");
return chain.proceed(chain.request());
}
Request authorisedRequest = chain.request().newBuilder()
.addHeader("Authorization", getAccessToken()).build();
PrintLog.error("retrofit 2","Authorization header is added to the url....");
return chain.proceed(authorisedRequest);
}}).build();
And add this client object to the retrofit object.
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //BaseURL always ends with "/"
.addConverterFactory(GsonConverterFactory.create())
.client(defaultHttpClient)
.build();
Now for every calls that you make using the retrofit object will add the "Authorization" header along with the url. And also we handle the condition that if the authorization value is empty, then we simply omit the Authorization header part for the request call.
From Retrofit:2.0
you have to use OkHttpClient.Builder() class to add Interceptors.
So you have to change your code like this.
OkHttpClient client = new OkHttpClient.Builder();
client.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", new SharedPreferencesUtil(getBaseContext()).getToken())
.header("Content-Type", "application/json")
.method(original.method(),original.body())
.build();
return chain.proceed(request);
}
}).build();

Saving data in windows phone received from WCF/web service .

Saving data in windows phone received from WCF/web service .
The response may be received after sometime so how to handle this situation.
Saving data is no problem but How to handel if data is received late
You can use this code (show the code from my project):
public void sendPost(string postData, Action<MyResponse, Exception> callback, CreateResponse creater)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UrlRequest);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "application/json";
webRequest.AllowAutoRedirect = true;
webRequest.BeginGetRequestStream(new AsyncCallback(getRequestStreamCallback), new Request()
{
HttpRequest = webRequest,
PostData = postData,
Url = UrlRequest,
CallBack = callback,
Creater = creater
});
}
private void getRequestStreamCallback(IAsyncResult asynchronousResult)
{
var request = (Request)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = request.HttpRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(request.PostData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
request.HttpRequest.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
}
private void getResponseCallback(IAsyncResult asynchronousResult)
{
var request = (Request)asynchronousResult.AsyncState;
try
{
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)request.HttpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var myResponse = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
MyResponse response_obj = request.Creater.CreateResponseObj();
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(myResponse)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(response_obj.GetType());
response_obj = (GYResponse)serializer.ReadObject(stream);
if (request.CallBack != null)
{
request.CallBack.Invoke(response_obj, null);
}
}
}
catch (WebException e)
{
if (request.CallBack != null)
{
request.CallBack.Invoke(null, e);
}
}
}
public void getInfo(string uid, Action<MyResponse, Exception> callback)
{
CreateResponse creater = new CreateResponseGetInfo();
string model = "User";
string method = "getInfo";
Params parametrs = new Params();
parametrs.Uid = uid;
//create yor request
string request = getRequestString(model, method, parametrs, Atoken);
sendPost(request, callback, creater);
}
So, you call method, which send request to web service postRequester.getInfo(uid, ResponseHandler) and use delegate for processing result.
private void ResponseHandler(MyResponse result, Exception error)
{
if (error != null)
{
string err = error.Message;
return;
}
else
{
var infoResponse = result as ResponseGetInfo;
if (infoResponse != null)
{
//result processing..
}
}
}
All the web requests you make in a Windows Phone app are Asynchronous. That means, you make a web request from your app and attach a handler to handle the response when it comes. In the response handler, you will have to take care of the response and do whatever you want with it.
Check this link Using WebClient and HttpWebRequest