Java: Server response is cut when stored into a string? - java

very strange problem, don't have any idea. Maybe you can help again - as so often :)
I create a simple UrlConnection and use the post-method. When I look into wireshark, everything is send right to me. I try to store the response into a string. And that string is a short version of the entire packet while it is closed right (with a /html-tag).
A diff in notepad gives me like this:
and in wireshark:
<a href="wato.py?mode=edithost&host=ColorPrinter ... muchmuchmore ...
This is the place where it seems to get its cut
Really strange stuff, now this is my code:
public void uploadCsv(File csvFile) throws CsvImportException, IOException {
String sUrl = String.format(urlBaseWato, hostAddress);
String csvFileContent = readFile(csvFile);
ParamContainer params = new ParamContainer().addParam("a", "a")
.addParam("b", b)
.addParam("c", "c");
URLConnection connection = new URL(sUrl).openConnection();
postData(connection, params);
String resp = getResponse(connection); // <---- broken string here :(
...
}
-
private void postData(URLConnection con, ParamContainer params) throws IOException {
int cLen = params.getEncodedParamString().getBytes().length;
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Cookie", authCookie.toString());
con.setRequestProperty("Content-Length", Integer.toString(cLen));
//Send request
DataOutputStream os = new DataOutputStream (con.getOutputStream());
os.writeBytes(params.getEncodedParamString());
os.flush ();
os.close ();
}
-
private String getResponse(URLConnection connection) throws IOException {
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
String response = "";
while ((line = in.readLine()) != null)
response +=line;
in.close();
return response;
}
Mysterious, I don't have the slightest idea. Can you help me?

Does using IOUtils help?
URLConnection connection = new URL(sUrl).openConnection();
IOUtils.toString(connection.getInputStream(), "UTF-8");
or even:
IOUtils.toString(new URL(sUrl), "UTF-8");
Even if not, always consider it first to reduce the amount of boilerplate in your code.

I guess I should make this an answer in case it's the problem and can get accepted. I've seen cases where closing the socket cuts off the stream that's already been written there. Try putting a Thread.sleep(5000) just in front of the socket closure.

Related

How to use HttpURLConnection in Android to post data?

I want to send json data via stream to the server, but I struggle to make it work.
I have the following method:
String data = "{\"id\":\"2633\",\"f_name\":\"Test\",\"l_name\":\"Aplikace\",\"city\":\"Nymburk\",\"address\":\"Testovaci 123456789 xyz\",\"psc\":\"288 02\"}";
private String httpPost(String urlString, String data, String session_per) {
StringBuffer sb = new StringBuffer("");
String s1 = "";
try {
URL url = new URL(urlString);
String s2 = "";
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
httpurlconnection.setUseCaches(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setRequestProperty("Cookie",session_per);
httpurlconnection.setRequestProperty("Authentication-Token", GlobalVar.KLIC);
httpurlconnection.setRequestProperty("Content-type", "application/json");
httpurlconnection.setAllowUserInteraction(false);
OutputStreamWriter outStrWrt = new OutputStreamWriter(httpurlconnection.getOutputStream());
outStrWrt.write(data);
outStrWrt.close();
String s3 = httpurlconnection.getResponseMessage();
//dataoutputstream.flush();
//dataoutputstream.close();
InputStream inputstream = httpurlconnection.getInputStream();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
int i;
while( (line = br.readLine()) != null) {
sb.append(line);
}
s1 = sb.toString();
}
catch(Exception ex)
{
ex.printStackTrace();
s1 = "";
}
return s1;
}
Can anyone tell me why this won't work? The cookies etc. are all correct. Did I miss something important? This is like the 6th method I am trying and I'm starting to get desperate :D
Thank you!
EDIT:
It succesfully connects and the server responds, but it doesn't update user data, as if the json didn't get to the server correctly.
If my Java code is correct there may be a server-side issue.
Try to use flush() method,you don't close this output stream before you read all bytes
outStrWrt.flush();
InputStream inputstream=httpurlconnection.getInputStream();
If you use Java 11, you can try to use HttpClient too.
E.g:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(new URI(urlString)).header("Cookie",session_per).header("Authentication-Token",GlobalVar.KLIC).header("Content-type","application/json").POST(HttpRequest.BodyPublishers.ofString(data)).build();
String datas=client.send(request,BodyHandlers.ofString());
return datas;

Sending post using HttpURLConnection

I have a node.js which waits for post with 2 parameters (name and pass):
app.post('/login.html', function (req, res) {
log.info(req.body);
userName = req.body.name;
pass = req.body.pass;
...
}
I'm trying to send post with the 2 parameters via simple java application, but I can't see that it arrive to the node.js.
what am I missing ?
The java code:
public static void main(String[] args) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://83.63.118.111:31011/login.html");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String str = "name='root'&pass='123456'";
//System.out.print(str);
writer.write(str);
writer.flush();
Thread.sleep(100);
writer.close();
os.close();
}
Your code will close when start send data (send and stop)
You should wait it done.
Add code after writer.flush();
Example get response:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
or just get responseCode:
int responseCode = urlConnection.getResponseCode();
Your program wait send request success or fail.
I think you use Thread.sleep(100); to wait send request, but it stop your Thread (don't send data to server)
Your code have req.body, Express.js don't have it, need use middleware body-parser.

Does Android have an intern Char Limit for a String? [duplicate]

This question already has answers here:
Why does LogCat not show the full message?
(2 answers)
Closed 8 years ago.
I work with HttpUrlConnection in my App and in my common Java Test and I implemented a method and that Method (common for both of them, so, identical!!!) behaves in Android case in another way.
Both of them can right receive an identical response from Server but in Java Test I can show this response while in Android App is chunked to 3200 Chars.
That's my Code
private String sendPost() throws Exception{
String url = "http://www.something.com/my_page.jsp?";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
String urlParameters ="param1=val1&param2=val2";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// return result
Log.i("TAG", "sendPost:: Response length : " + response.length()); // <- This line returns the same length!!!
return response.toString();
}
All I can get of this object con from Class HttpUrlConnection like ContentLength, ContentType, etc is the same in both of these cases, therefore I suspect, there must be an intern Setting/Parameter of String/StringBuffer in Android, which distinguishes these case but I don't know what. readLine reads the same or at least the same number of chars cause the length of response is the same in both of cases.
If you could say me, what is wrong, I'd be very thankful.
Kind Regards
I can't understand your description of the symptoms; i.e. why you think that something is being truncated.
However, I can assure you that it is NOT due to a limit on the length of String or StringBuffer.
Those two classes do have a limit, but it is 2**31 (i.e. >2 billion) characters. You will typically get an OutOfMemoryError before your buffer gets that big.

tcp/ip open connection

currently i am using the following code to interact with server
public String connectToserverforincomingmsgs(String phonurl, String phno)
throws IOException {
URL url = new URL(phonurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
// Allow Outputs
con.setDoOutput(true);
con.connect();
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
con.getOutputStream(), "UTF-8"));
// give server your all parameters and values (replace param1 with you
// param1 name and value with your one's)
writer.write("sender_no=" + phno);
writer.flush();
String responseString = "";
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
responseString = responseString.concat(line);
}
con.disconnect();
return responseString;
}
how could i make tcp connection .right now i don't have any idea . i am new to android and java aswell so any sample code about the tcp connection would be appreciated
To create a TCP Connection you need to Use Socket:
Socket socket = new Socket(host_name_or_ip_address, port_no);
To Send Data use socket.getOutputStream()
To Receive Data use socket.getInputStream()
Just replace HttpURLConnection with Socket. It works pretty much the same

how to get data to a servlet which is send using httpcommunicator with post method

I am trying to send data using httpcommunicator class.
here is my code.
public String postData(String address,String dataToBePosted) throws MalformedURLException,IOException,ProtocolException{
/** set up the http connection parameters */
HttpURLConnection urlc = (HttpURLConnection) (new URL(address)).openConnection();
urlc.setRequestMethod("POST");
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
/** post the data */
OutputStream out = null;
out = urlc.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(dataToBePosted);
writer.close();
out.close();
/** read the response back from the posted data */
BufferedReader bfreader = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
StringBuilder builder = new StringBuilder(100);
String line = "";
while ((line = bfreader.readLine()) != null) {
builder.append(line+"\n");
}
bfreader.close();
/** return the response back from the POST */
return builder.toString();
I am sending it to my servlet.
but i dint know how to retrieve it.
is there any method like getPerameter or else?
Thank you.
I haven't tried your code, but it looks reasonable to me, with the possible exception that you don't appear to be disconnecting your HttpUrlConnection when you've finished with it.
When you run the code, what happens? Do you see an exception? Can you tell that it has reached the servlet? What do you see if you look at the contents of builder by doing System.out.println(builder.toString()?

Categories

Resources