简体   繁体   中英

Sending Data from Android to PHP

at first, I'm new in these things, so I hope that this is not a very basic question. I am trying to get data in my Android application, from a PHP web, the PHP have some functions that returns me some data, but to call them, I need to send and string first from the android application. I'm trying to search how to do it but I don´t find anything. Can anyone help me please? Thanks

 public void getServerData() throws JSONException, ClientProtocolException, IOException {               

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);
        HttpPost request = new HttpPost(url);

        request.setHeader( "Content-Type", "application/json" );        

        JSONObject json = new JSONObject();         
        json.put("type", "register");
        json.put("user_name", "colors");
        json.put("user_password", "colors123");

        Log.i("jason Object", json.toString());        

        StringEntity se = new StringEntity(json.toString());                 
        se.setContentEncoding("UTF-8");
        se.setContentType("application/json");    
        request.setEntity(se);        

        HttpResponse response = client.execute(request);        
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        String _response = convertStreamToString(is);
        System.out.println("res  " + _response);           
        int res_code = response.getStatusLine().getStatusCode();
        System.out.println(" code " +res_code); 
    }               
    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 1856);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM