Android应用发送字符串以显示在网页上

时间:2017-08-13 18:39:13

标签: php android

我一直试图创建Android应用和网页数月,应用程序向网站发送一个简单的字符串,网站显示该文本。我已经尝试了很多教程,但它们都不完整或不完整。

由于我在编码方面只是一个n00b,我无法分辨这些建议是整个故事还是仅仅是故事的一部分。事实证明,我只是故事的一部分。

我的目标是:创建一个Android应用和网页,应用程序向网站发送一个简单的字符串,网站显示文本供所有人查看。最后一部分我没有在我的问题中提及。所以要求完整有助于得到正确的答案。

我必须采取以下几个步骤:

  1. 注册域名(我做过)
  2. 签订托管服务(我做过)
  3. 将带有HasH代码的php文件(见下文)上传到该网页顶级目录中的网页文件管理器,确保没有为该域或子域运行内容管理器(这里我犯了一个错误:我让Parallels Presence Builder在目标域上运行。因为它总是使用模板我无法发布php文件的“干净”版本。这导致我的网页以<!DOCTYPE开头回馈垃圾信息我创建了一个没有内容管理的新子域名,并使用Hash的php代码上传了一个php文件。它工作得非常好。)
  4. 然后我使用哈希的代码创建了Android应用程序(见下文,不要忘记.jar文件,不要忘记将.jar文件添加为库!)。
  5. 由于我的问题不完整,Hash的代码不处理网页必须显示文本以供所有人查看的部分。由于php是每个用户的个人用户,我必须添加代码。
  6. 见这里:

    <?php
    $msg = $_POST['msg'];
    if($_SERVER['REQUEST_METHOD']=='POST'){
    $myfile = fopen("yourfilename.txt", "a") or die("Unable to open file!");
    fwrite($myfile, $msg . "\n");
    fclose($myfile);    
    }
    
    $myfile = fopen("yourfilename.txt", "r") or die("Unable to open file!");
    echo fread($myfile,filesize("yourfilename.txt"));
    fclose($myfile);
    ?> 
    

1 个答案:

答案 0 :(得分:1)

好的,让我给你一个非常简单的方法来连接你的应用程序和PHP服务页面...... 首先,你必须确保你已经有这个库: 1- http-core-4.1.jar 2- httpclient-4.0.3.jar

然后创建一个新的类名“JSONParser”并粘贴此代码:

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

好了,现在进入你的主要活动并按照这样做:

public class MainActivity extends AppCompatActivity {
JSONParser jparser = new JSONParser(); 
 ProgressDialog pdialog;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String msg = "Hello";

new connector().execute(msg); //This will create a new thread to connect with your service page.


}

//The AsyncClass connector..



 class connector extends AsyncTask<String,String,String> {
        @Override
        protected void onPreExecute(){
            pdialog = new ProgressDialog(MainActivity.this);
            pdialog.setMessage("Sending Hi...");
            pdialog.setCancelable(false);
            pdialog.setIndeterminate(false);
            pdialog.show();
        }
        //ArrayList to carry your values
        List<NameValuePair> data = new ArrayList<>();

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

            try {

                    data.add(new BasicNameValuePair("msg",params[0])); //here we sit the key "msg" to carry your value which you passed on thread execute.

  //Then create the JSONObject to make the rquest and pass the data(ArrayList).              
 JSONObject json = jparser.makeHttpRequest("Http://example.com/mypage.php","POST",data);

/*In case you want to receive a value from your page you should do something like this..
String getString = json.getString("key1");
Int getInt = json.getInt("key2");
key1,key2 are keys that you send from your page.
*/





            } catch (Exception e) {
               /* Any Exception here */
            }

            return null;

        }

        @Override
        protected void onPostExecute(String file_url){
            pdialog.dismiss();
              // This After the thread did it's operate
/* For Example you Toast your key1,key2 values :D*/

            }
    }



}

在您的PHP页面中,您应该执行以下操作..

<?php
//In case of receive..
$msg = $_POST['msg']; 
echo $msg;

//In case of send..
$values = array();
$values["key1"] = "Hello this is key1";
$values["key2"] = "Hello this is key2";
echo json_encode($values); //this will make a json encode which you can get it back in your application ;)

?>

希望它有帮助:),对不起我的坏英语:v