Java: server response gets cut when stored in string?

very strange problem, I have no idea. You may be able to help again - so often :)

I am creating a simple UrlConnection and using post-method. When I look in the wires, everything goes straight to me. I am trying to store the answer in a string. And this line is the short version of the whole package, while closed correctly (with the / html tag).

The difference in notepad gives me like this:

<a href="wato.py?mode=..."></a>

      

and in wireshark:

<a href="wato.py?mode=edithost&amp;host=ColorPrinter ... muchmuchmore ...

      

This is where he seems to get his cut

Really weird 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 have no idea. Can you help me?

+3


source to share


2 answers


Is 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 count first to reduce the amount of boilerplate in your code.

+1


source


I guess I should answer this question if this is a problem and can be accepted. I've seen cases where closing a socket cuts off a stream that was already written there. Try putting Thread.sleep (5000) right before closing the socket.



0


source







All Articles