0

I use a simple WebServer from http://www.java2s.com/Code/Java/Network-Protocol/AverysimpleWebserverWhenitreceivesaHTTPrequestitsendstherequestbackasthereply.htm

and Android code from Sending json object via http post method in android

In my main Activity:

AsyncT asyncT = new AsyncT();
asyncT.execute();

Class:

class AsyncT extends AsyncTask<Void,Void,Void>{

    @Override
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL(""); //Enter URL here
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
            httpURLConnection.connect();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("para_1", "arg_1");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }


}

The connection is established without any errors ("HostConnection::get() New Host Connection established"). However, I am not able to get in my Java server any information from the request. When I read from input stream

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    System.out.println(in); 

I get java.io.BufferedReader@4d7hge12

And this outputs nothing:

String line;
    while ((line = in.readLine()) != null) {
      if (line.length() == 0)
        break;
      System.out.println(line);
    }
Community
  • 1
  • 1
kjdkfjsdo8
  • 97
  • 12
  • 1
    Have a look at the library: https://square.github.io/retrofit/ makes things like this very easy – DZDomi Dec 19 '16 at 13:26

2 Answers2

0

Don't re-invent the wheel and use a library for this.

For example okhttp:

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

If you want to call a REST-API you can use retrofit (which is build ontop of okhttp)

larsgrefer
  • 2,735
  • 19
  • 36
  • I implemented it now using OKHttp but it did not solve my problem. Probably something is wrong with the java server code. – kjdkfjsdo8 Dec 19 '16 at 15:46
0

Assuming you're doing this as a learning exercise, so using another library isn't what you're looking for, I would suggest a couple of things:

(1) install Wireshark and see what the actual response coming back the server is, does it look sensible?

(2) break that line of code out into separate lines, is the InputStream / InputStreamReader null?

Andy Nugent
  • 859
  • 7
  • 21
  • In Wireshark I see only one packet with Info "HTTP/1.1 200" from server port to client port, but I don't see any POST request. – kjdkfjsdo8 Dec 19 '16 at 15:45
  • I'd suggest getting it working in cUrl or similar and then trying again in Java. – Andy Nugent Dec 19 '16 at 16:30
  • with curl it is fine GET / HTTP/1.1 Host: 127.0.0.1:45321 User-Agent: curl/7.13.0 Accept: */* So looks like Android code is wrong even that a connection is established and server confirms it – kjdkfjsdo8 Dec 19 '16 at 16:58
  • I rewrote the code using official tutorial and it solved the problem, don't know exactly what it was but now it is working – kjdkfjsdo8 Dec 19 '16 at 20:32