0

起初,我对这些东西很陌生,所以我希望这不是一个非常基本的问题。我正在尝试从 PHP 网络获取我的 Android 应用程序中的数据,PHP 有一些函数可以返回一些数据,但是要调用它们,我需要先从 android 应用程序发送和字符串。我正在尝试搜索如何做到这一点,但我什么也没找到。任何人都可以帮助我吗?谢谢

4

1 回答 1

1
 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();
    }
于 2012-06-01T09:06:38.487 回答