How to do a Http POST of a string with rxSendStream of io.vertx.reactivex.ext.web.client.WebClient - rx-java2

I am new to Vertx and Rx Java. I want to do a Http POST , but my content is a string. Here is my code :
Single<HttpResponse<Buffer>> single = webClient
.post(apiUrl)
.rxSendStream(body);
and body can be any of the following:
Flowable<Buffer> body or
Observable<Buffer> body or
Buffer body
My question is how do i convert body to any of the above types

The easiest way is this:
WebClient webClient = WebClient.create(vertx);
String body = "";
webClient.post(apiUrl)
.rxSendBuffer(Buffer.buffer(body))
.subscribe(resp -> {
System.out.println(resp.body().toString());
});

Related

StreamReader reads \u00fc but Postman reads OK

Probably duplicate question but I couldn't find an answer for my problem. I have this code to call a web service:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.21.122.1:5001/autocomplete");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//tried this too: httpWebRequest.Accept = "gzip, deflate";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write("{ \"message\" : \"mü\" }");
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
response = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
But no matter what Encoding I tried with StreamReader() c'tor, I get this response or worse: {"words":["m\u00fc\u015fteri","m\u00fc\u015fterisiyim""]}
When I use Postman or SoapUI to call the same service with the same request: {"message": "mü"},
response looks ok: {"words": ["müşteri","müşterisiyim"]}
Strange thing is: The same code works OK with many other services. It is only this specific service that the reponse is not correctly encoded. We believe there is a programming error with the service, but what I wonder is how Postman or SoapUI handles this. There should be a control in their code and if the response contains "\uxxxx", then Postman or SoapUI decodes it again.
I've checked all request / response headers in Postman and SoapUI with no luck. What can be the reason?
You have to make sure that your request is encoded correctly:
Set the Content Type to:
httpWebRequest.ContentType = "application/json;charset=UTF-8";
Check if request body is also UTF-8 encoded. Set the StreamWriter encoding to UTF-8 as well:
...
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
...
If you are getting the request content from other source, make sure to read it also using UTF-8 encoding.
Regex.Unescape(response) worked like a charm, thanks JosefZ!

Get SOAP Reply in ASP.NET Webservice

I created a SOAP WebService to receive a request. I want to log the SOAP messages with envelope.
I discovered how get the request message, but I don't discovered how can I get the reply message.
To get the XML Request, I use the code below.
// Create array for holding request in bytes
byte[] inputStream = new byte[HttpContext.Current.Request.ContentLength];
// Read the entire request input stream
HttpContext.Current.Request.InputStream.Read(inputStream, 0, inputStream.Length);
// Set stream position back to beginning
HttpContext.Current.Request.InputStream.Position = 0;
// Get the XML request
string xmlRequestString = Encoding.UTF8.GetString(inputStream);
To get the reply, I tried do this into the Dispose method, but I couldn't make it work.
The InputStream works fine.
The Request SOAP XML I get propertelly. I need a way to get de SOAP XML that my web method replay to the caller. Into the WebMethod the Response is not complet. So I tried use the Dispose Method, but I have the same problem. The dispose method is call before .Net Framework return the reply to caller.
I need a way to log the SOAP XML Request abd the SOAP XML Replay.
The code below get XML Request fine:
[WebMethod]
public ActivityCCPResponseOutput Request(ActivityCCPRequestInput ActivityCCPRequestInput)
{
XmlDocument xmlSoapRequest = new XmlDocument();
Stream receiveStream = HttpContext.Current.Request.InputStream;
receiveStream.Position = 0;
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
xmlSoapRequest.Load(readStream);
string xmlSOAPRequest = xmlSoapRequest.InnerXml;
...
}
In the code below, I couldn't get the reply. Probably, there is a different way to do this.
void IDisposable.Dispose()
{
XmlDocument xmlSoapResponse = new XmlDocument();
// In this point HttpContext.Current.Response.OutputStream is empty
Stream responseStream = HttpContext.Current.Response.OutputStream;
responseStream.Position = 0;
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
xmlSoapResponse.Load(readStream);
string xmlSOAPReply = xmlSoapResponse.InnerXml;
}

How to consume stream response body using Apache HC

I am using a REST API, which returns continouous real-time streaming response body. The response body stream is opening continuously. I want to read this streamed response through Apache Http Components.
Any help is appreciated.
[UPDATE]
My response is similar to this demo
https://github.com/brianhempel/stream_json_demo
You have to set up a client to send and recieve stream response from API.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/something");
post.setHeader("Referer", "http://localhost/something");
post.setHeader("Authorization", "Basic (with a username and password)");
post.setHeader("Content-type", "application/json");
// if you need any parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("paramName", "paramValue"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
Header encodingHeader = entity.getContentEncoding();
// you need to know the encoding to parse correctly
Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 :
Charsets.toCharset(encodingHeader.getValue());
// use org.apache.http.util.EntityUtils to read json as string
String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
JSONObject o = new JSONObject(json);
You can get apache HTTP client library from here http://hc.apache.org/ and commons-io

Handling form data for application/x-www-form-urlencoded contentType

I have a textarea in a jsp page and the contents of that are processed in a Servlet.
I thought the contentType was multipart so I figured I'd use getFormField() and getString() methods to extract the values but this throws an exception saying
the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded
When I use request.getParameter("textAreaID") it is always null. How do I handle this situation? Any help would be appreciated. Please let me know if the question is not framed in a proper manner before downvoting. Thanks in advance.
If u want to extract values of many fields,you can use getParameterNames() method
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String parameter = (String) paramNames.nextElement();
String parameterValue = (String) request.getParameter(parameter);
System.out.println("*****" + parameter + " - " + parameterValue);
}

Sending protocol buffers via REST

I am trying to implement protocol buffers for client/server using REST.
I am still a bit confused if I need to send protocol buffers request in byte format?
I mean, in my client code, do I need to serialize object to byte array?
For example
protoRequest.build.toByteArray()
And in the server, do I need to c
#POST
#Consumes("application/octet-stream")
public byte[] processProtoRequest(byte[] protoRequest) {
ProtoRequest.Builder request = ProtoRequest.newBuilder();
request.mergeFrom(protoRequest)
}
Is this the right thing to do?
Thanks
David
You can use input stream for this purpose. Server Side Code will be look like the below code
#POST
public Response processProtoRequest(#Context HttpServletRequest req) {
ProtoRequest protoRequestObj = ProtoRequest.parseFrom(req.getInputStream());
///process protoRequestObj and convert into byte arry and send to clinet
return Response.ok(protoRequestObj.toByteArray(),
MediaType.APPLICATION_OCTET_STREAM).status(200).build();
}
client side will look like this:
ProtoRequest protoRequestObj = ProtoRequest.newBuilder(). //protocol buffer object
setSessionId(id).
setName("l070020").
build();
DefaultHttpClinet httpClinet = new DefaultHttpClinet();
HttpPost request = new HttpPost("http://localhost:8080/maven.work/service/mainServices/protoRequest");
request.addHeader("accept","application/octet-stream");
request.setEntity(protoRequestObj.toByteArray());
HttpResponse response = httpClient.execute(request);
I have written a Step by Step tutorial about how to produce/consume a protocol buffer stream in a web service, using Jersey as the client JAX-RS implementation. I hope it will help you. :)
Server side :
#GET
#Path("/{galaxy}")
#Consumes(MediaType.TEXT_HTML)
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getInfo(#PathParam("galaxy") String galaxyName){
if(StringUtils.equalsIgnoreCase("MilkyWay", StringUtils.remove(galaxyName, ' '))){
// The following method would call the DTO Galaxy builders.
Galaxy milkyWay = MilkyWayFactory.createGalaxy();
// This is the important line for you where where the generated toByteArray() method takes responsibility of serializing the instance into a Protobuf format stream
return Response.ok(milkyWay.toByteArray(),MediaType.APPLICATION_OCTET_STREAM).status(200).build();
}
return Response.status(Status.NOT_FOUND).build();
}
Client side :
String serverContext = "learning-protobuf3-ws-service";
String servicePath = "ws/universe/milkyway";
String serviceHost = "localhost";
Integer servicePort = 8080;
javax.ws.rs.client.Client client = javax.ws.rs.client.ClientBuilder.newClient();
javax.ws.rs.client.WebTarget target = client.target("http://"+serviceHost+":"+servicePort+"/"+serverContext)
.path(servicePath);
InputStream galaxyByteString = target.request(MediaType.TEXT_HTML)
.header("accept",MediaType.APPLICATION_OCTET_STREAM)
.get(InputStream.class);
Galaxy galaxy = Galaxy.parseFrom(IOUtils.toByteArray(galaxyByteString));
You could encode the result of SerializeToString using base64.