http post request not sending parameters in Blackberry 5.0 - http

I've been working on a BlackBerry post request, and the request is getting sent, but the parameters don't seem to be. Here is my code:
HttpConnection httpConnection = (HttpConnection) Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("time", "1314144000");
System.out.println("url: " + httpConnection.getURL());
byte[] postData = encPostData.toString().getBytes("UTF-8");
System.out.println("post data: " + encPostData.toString());
httpConnection.setRequestProperty("Content-length", String.valueOf(postData.length));
System.out.println("url: " + httpConnection.getURL());
System.out.println("message:" + httpConnection.getResponseMessage());
OutputStream os = httpConnection.openOutputStream();
os.write(postData);
os.flush();
os.close();
The response I get from the server(which we set up) is that we didn't send a time stamp. Is there something wrong with my
encPostData.append("time", "1314144000");
code?

Your call to getResponseMessage() before writing the post data is forcing a response before anything has been written on the connection.
System.out.println("message:" + httpConnection.getResponseMessage());
Move that to the end, after the output stream data has been written, and I think it will work better for you.

Make the http connection in read write mode.Might be that is the problem making http connection without mode link
HttpConnection connection = (HttpConnection) Connector.open("url", Connector.READ_WRITE);
See below link for making http connection.
blackberry server connection problem

Related

What does Encountered end-of-stream mid-frame mean when it spits this out on the GRPC server?

I am sending data to grpc service and getting error message in return:
Encountered end-of-stream mid-frame
What does this mean. the connection was interrupted or something else like not enough data sent across. Was it a failure of my client to send enough data of the message over or was it some connection break in the middle of processing. I dont have enough information from this.
If you dont know whats wrong here just tell me if it means the connection closed too early during processing or the datafeed was just not as long as expected but there was no connection problem.
I am using this filter from Envoy proxy (Lyft):
I am using this bridge from Envoy:
https://www.envoyproxy.io/docs/envoy/latest/configuration/http_filters/grpc_http1_bridge_filter
It asks for zero byte up front and 4 bytes with big indian of the length.
For me its a long ugly and meaningless message:
Jul 23, 2019 2:26:06 PM io.grpc.netty.shaded.io.grpc.netty.NettyServerStream$TransportState deframeFailed
WARNING: Exception processing message
io.grpc.StatusRuntimeException: INTERNAL: Encountered end-of-stream mid-frame
at io.grpc.Status.asRuntimeException(Status.java:524)
at io.grpc.internal.AbstractServerStream$TransportState.deframerClosed(AbstractServerStream.java:238)
at io.grpc.netty.shaded.io.grpc.netty.NettyServerStream$TransportState.deframerClosed(NettyServerStream.java:155)
at io.grpc.internal.MessageDeframer.close(MessageDeframer.java:229)
at io.grpc.internal.MessageDeframer.deliver(MessageDeframer.java:296)
at io.grpc.internal.MessageDeframer.request(MessageDeframer.java:161)
at io.grpc.internal.AbstractStream$TransportState.requestMessagesFromDeframer(AbstractStream.java:205)
at io.grpc.netty.shaded.io.grpc.netty.NettyServerStream$Sink$1.run(NettyServerStream.java:100)
at io.grpc.netty.shaded.io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
at io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:333)
at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
14:26:06.445 [grpc-default-worker-ELG-3-2] DEBUG io.grpc.netty.shaded.io.grpc.netty.NettyServerHandler - [id: 0xd01ed34c, L:/127.0.0.1:9009 - R:/127.0.0.1:48042] OUTBOUND RST_STREAM: streamId=45 errorCode=8```
Is there something wrong with the client?
//Define a postRequest request
HttpPost postRequest = new HttpPost("http://10.10.xx.xx:31380/com.test.EchoService/echo");
//Set the API media type in http content-type header
postRequest.addHeader("content-type", "application/grpc");
int messageLength=EchoRequest.newBuilder()
.setMessage("Hello"+ ": " + Thread.currentThread().getName())
.build().getMessageBytes().toByteArray().length;
byte[] lengthBytes = ByteBuffer.allocate(4).putInt(messageLength).array();
byte[] zeroByte = {0};
byte[] messageBytes = EchoRequest.newBuilder()
.setMessage("Hello" + ": " + Thread.currentThread().getName())
.build().getMessageBytes().toByteArray();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(zeroByte);
baos.write(lengthBytes);
baos.write(messageBytes);
byte[] c = baos.toByteArray();
//Set the request post body
StringEntity userEntity = new StringEntity(content);
ByteArrayEntity bae = new ByteArrayEntity(baos.toByteArray());
postRequest.setEntity(userEntity);
//Send the request; It will immediately return the response in HttpResponse object if any
HttpResponse response = httpClient.execute(postRequest);
//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 201)
{
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
the error message means, the server received partial data, and it doesn't expect more data coming since the end of stream is true.
based on the error message, the length is probably larger than actual proto payload.

want to verify http no 4xx or 5xx HTTP responses come back through selenium webdriver

How to check the this http response in selenium web driver? Is it possible to verify the same?
If you want to assert on the status of AJAX requests, then you can create a Browsermob proxy and use it's REST API to verify each request
Try this. It work for you :P
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String output;
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);}
Once done verify the response code(using asserts). Let me know if u still face issue.

Performance tuning when calling a WebService using HttpURLConnection

I am trying to call a webservice that return too much data just to extract a small piece of data.
So, I decided not to use the standard Client which is generated by Java.
I use the following code to do the connection:
HttpURLConnection connection;
byte[] requestData = .....
URL url = new URL(wsUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Content-Length", String.valueOf(requestData.length));
connection.connect();
OutputStream connOs = connection.getOutputStream();
connOs.write(requestData);
connOs.close();
InputStream is = connection.getInputStream(); // <<< THIS IS THE MOST TIME CONSUMING, it takes about 70 ms
byte[] rply = stream2Bytes(is);
is.close();
connection.disconnect();
The most time is consumed in the call to connection.getInputStream(); which it takes about 70ms.
I am trying setting many request headers to reduce this time but cannot reach.
My understanding it that the HttpUrlConnection uses HTTP1.1 protocol that uses Connection=KEEP-ALIVE header by default so that the underlying TCP connection is reused.
connection.getInputStream(); - function which wait for server response... you can't speed up this proccess.

Why does HttpWebRequest fail the first time and then works OK?

I am truing to integrate fusemail in asp.net 2.0. I am using HttpWebRequest for requesting the API pages. It has recently come to my notice that HttpWebRequest fails the first time and then continues and subsequent requests succeed.
say ( i know if i use goto it is a bad programming approach) if i use this code
retry:
try
{
Uri uri = new Uri("http://www.fusemail.com/api/request.html");
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.PreAuthenticate = true;
request.Method =
WebRequestMethods.Http.Post;
//request.ReadWriteTimeout = System.Threading.Timeout.Infinite;
//request.Timeout = System.Threading.Timeout.Infinite;
request.ContentLength = data.Length;
request.ContentType =
"application/x-www-form-urlencoded";
//request.UserAgent = Request.UserAgent;
request.UserAgent = "Mozilla/4.0";
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = true;
//request.Accept = "Accept: text/html,application/xhtml+xml,application/xml";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
//Response.Write(tmp);
if (!String.IsNullOrEmpty(tmp))
{
return tmp;
}
}
return String.Empty;
}
catch (WebException ex)
{
goto retry;
}
it works after failing once. i am writing to a text file in case of an error and after i failed request it works the second time. I am using ASP.Net 2.0 and the website is hosted on IIS 7 with Windows Server 2008 Standard. Also pinging the API address it fails the first time and then responds
C:\>ping 67.207.202.118
Pinging 67.207.202.118 with 32 bytes of data:
Reply from 192.168.0.253: **Destination host unreachable**.
Reply from 67.207.202.118: bytes=32 time=218ms TTL=49
Reply from 67.207.202.118: bytes=32 time=218ms TTL=49
Reply from 67.207.202.118: bytes=32 time=217ms TTL=49
Ping statistics for 67.207.202.118:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 217ms, Maximum = 218ms, Average = 217ms
The first time it fails in HttpWebRequest it fails with this error
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 67.207.202.118:80
Is there an authentication issue the first time?. i read on some forums it first sends a 401 Unauthorized and then it can connect. I am unable to verify this using Fiddler.
Is there anything wrong with IIS configuration?
This is not a programming issue at all, I have faced a similar problem later and it was a network configuration problem due to ISA server / Firewall settings.
You have to contact your network administrator to check this issue.
I wish this helped you.
Yours,
Mohamed Kamal Elbeah
Senior .Net Developer
I recently came by this same issue. The solution in my case involved my testing environment, since I had multiple Ethernet adapters connected to my computer. While you may have a different IP for each of your Ethernet adapters, if they are all assigned to the same subnet this may cause a problem. The TCP connection is only attempted using one NIC at a time. So in my case, on the first try it would attempt the connection on one adapter that was not connected to my remote host, then on the second try it would connect using the second adapter which was connected. - Hope this helps someone.

WebRequest problem, response before request-body

I'am using the WebRequest class in .net and POST data to a server which is responding with a Response.
The wierd thing is that its working when I started fiddler to analyze my network traffic, but without fiddler it isn't.
So i started to analyze the package which is sent to and from my computer with WireShark. With in this program its simple to follow the TCP-stream. So when I had fiddler on, I can see the correct Request-header/body is sent, and gets the Response-header/body. The strange part is when i dont use fiddler the Request-header is sent, then i´ve got the Response-header/body, and finally the request-body in the end of the TCP-stream.
Here is my code i've been elaborating:
string lcUrl = "http://XX.XX.XXX.XX";
// *** Establish the request
HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(lcUrl);
string lcPostData = testdata;
loHttp.Method = "POST";
byte [] lbPostBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(lcPostData);
loHttp.ContentLength = lbPostBuffer.Length;
loHttp.Credentials = CredentialCache.DefaultCredentials;
//loHttp.SendChunked = true;
loHttp.ServicePoint.Expect100Continue = false;
Stream loPostData = loHttp.GetRequestStream();
loPostData.Write(lbPostBuffer, 0, lbPostBuffer.Length);
loPostData.Close();
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(loWebResponse.GetResponseStream(), enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
Please use following code. Seems that you have problems with time when underlying stream are send to remote server.
string lcUrl = "http://XX.XX.XXX.XX";
// *** Establish the request
HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(lcUrl);
string lcPostData = testdata;
loHttp.Method = "POST";
byte[] lbPostBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(lcPostData);
loHttp.ContentLength = lbPostBuffer.Length;
loHttp.Credentials = CredentialCache.DefaultCredentials;
//loHttp.SendChunked = true;
loHttp.ServicePoint.Expect100Continue = false;
using (Stream loPostData = loHttp.GetRequestStream())
{
loPostData.Write(lbPostBuffer, 0, lbPostBuffer.Length);
}
string lcHtml;
using (HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse())
{
Encoding enc = System.Text.Encoding.GetEncoding(1252);
using (StreamReader loResponseStream = new StreamReader(loWebResponse.GetResponseStream(), enc))
{
lcHtml = loResponseStream.ReadToEnd();
}
}
// Perform processing of data here....
Also I could suggest you add following code in the app.config file for your application. This is helps when server returns response that not conforms with way how .NET handle HTTP request.
<configuration>
<system.net>
<settings>
<httpWebRequest
useUnsafeHeaderParsing="true"
/>
</settings>
</system.net>
</configuration>
I have a suspicion that the client is waiting for the "HTTP/1.1 100 continue" response from the server. This is how it works. When you are posting data to the server, sometimes the server might not be ready to accept the data just yet. For eg, it wants to authenticate the client first.
So, when you send a POST request, the client just sends the request headers, with an "Expect: 100-continue" appended.
POST /url HTTP/1.1
Server: Server-name/fqdn
Content-Length: 100
Expect: 100-continue
If the server is ready to receive the data it responds with:
HTTP/1.1 100 continue
Server: server-name/fqdn
Now, the client can send the data.
However if the server is not ready to receive the data, and wants to authenticate the client, it will respond with a different status code.
If you post your wireshark trace to pastebin.com I can verify, but I suspect this is what is happening.
The reason you dont see this in fiddler might be that fiddler is using HttpListener to listen to HTTP request, and HTTP listener hides the intermediate response like 100-continue from the app (in this case fiddler).

Resources