user1398478
user1398478

Reputation: 43

Sending JSON From Android to PHP

I've been struggling a bit on sending JSON objects from an application on android to a php file (hosted locally). The php bit is irrelevant to my issue as wireshark isn't recording any activity from my application (emulation in eclipse/ADK) and it's almost certainly to do with my method of sending:

      try {
        JSONObject json = new JSONObject();
        json.put("id", "5");
        json.put("time", "3:00");
        json.put("date", "03.04.12");
        HttpParams httpParams = new BasicHttpParams();
        HttpClient client = new DefaultHttpClient(httpParams);
        //
        //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" + 
        //             "json={\"UserName\":1,\"FullName\":2}";
        String url = "http://localhost/datarecieve.php";

        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                "UTF8")));
        request.setHeader("json", json.toString());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        if (entity != null) {
            InputStream instream = entity.getContent();

        }
    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }

I've modified this from an example I found, so I'm sure I've taken some perfectly good code and mangled it. I understand the requirement for multi-threading so my application doesn't hang and die, but am unsure about the implementation of it. Would using Asynctask fix this issue, or have I missed something else important?

Thankyou for any help you can provide.

Upvotes: 0

Views: 573

Answers (2)

Rajesh
Rajesh

Reputation: 15774

Assuming that you are using emulator to test the code, localhost refers to the emulated environment. If you need to access the php hosted on your computer, you need to use the IP 10.0.2.2 or the LAN IP such as 192.168.1.3. Check Referring to localhost from the emulated environment

You can refer to Keeping Your App Responsive to learn about running your long running operations in an AsyncTask

Upvotes: 1

skygeek
skygeek

Reputation: 1568

you should use asynctask or thread, because in higher versions of android it doesn't allow long running task like network operations from ui thread.

here is the link for more description

Upvotes: 1

Related Questions