1

大家好,我正在尝试将我的 JSONArray 发送到 php 页面我得到 HTTP//1.1 200 但我仍然无法在我的 php 页面中显示它,我仍然不知道我是否成功发送它在这里是我的安卓代码

public void sendJson() {

                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;

                try{
                    HttpPost post = new HttpPost("http://sap-sp-test.dff.jp/sp.php/ranking/index");
                    Log.i("entry", MixiActivity.entry.toString());

                    ArrayList<NameValuePair> nVP = new ArrayList<NameValuePair>(2);  
                    nVP.add(new BasicNameValuePair("json", MixiActivity.entry.toString()));
                    post.setEntity(new UrlEncodedFormEntity(nVP));
                    response = client.execute(post);
                    Log.i("postData", response.getStatusLine().toString());
                }
                catch(Exception e){
                    e.printStackTrace();
                    Log.i("error", e.getMessage());
                }

    }

PHP 代码

$data =  $_POST['json'];
echo $data;

我已经在这里尝试了一些示例,但是我仍然无法发送数据,并且当我尝试使用日志打印它时 JSON 数组(MixiActivity.entry)不为空,日志显示 JSON 数组的正确值但我可以'不要把它发送到 PHP 请帮我解决这个问题

非常感谢

尼可

4

2 回答 2

2

您可以尝试像这样在 post.setEntity() 中添加编码...

post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

在我看来,其他一切都很好。如果这不起作用,那么您也可以尝试使用 android 中的 JSON 库直接对其进行编码并将该数据传递给页面使用

HttpPost httppost = new HttpPost("http://your/url/path/");  
httppost.addHeader("Content-Type", "application/json");
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));

然后在php中你可以通过这段代码访问它

$json = file_get_contents('php://input');
$obj = json_decode($json);
$name = $obj->{'name'};

或者

您还可以尝试通过 php 文件中的 $_REQUEST 发出获取请求或访问数据。无论您使用什么,都正是您所需要的。

或者

试试这个,这是一个工作代码......它是一个可以直接用于将数据传递到文件的类。使用 :: 静态调用函数,并导入所有需要的 json 类

public class RestClient {

private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    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();
}




public static String connectSend(){

    /*
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, 30000);
    HttpConnectionParams.setSoTimeout(httpparams, 30000);
    */

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://path/to/your/php/file");   

    httppost.addHeader("Content-Type", "application/json");

    JSONObject json = new JSONObject();
    try {
        json.put("item0", "data0");
        json.put("item1", "data1");
        json.put("item2", "data2");
        json.put("item3", "data3");
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


    try {
        httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
        //httppost.setHeader("json", json.toString());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = RestClient.convertStreamToString(instream);


            return result;
        }


    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    } 
    catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    return "false";

}
于 2012-07-23T09:29:26.177 回答
1

最后我放弃了 android 中的 http post 现在我使用 javascript 从 android 获取 jsonarray

有了这个

公共类 JavaScriptInterface { 上下文 mContext;

         JavaScriptInterface(Context c) {
             mContext = c;
         }

         public String load() {
             String JS = JsonArray.toString();
             return JS;
         } }

并在 HTML

 function loadJSON()        
{           
var jsonData = Android.load();
var myDictionary = [];          
myDictionary["jsonData"] = jsonData;

post(myDictionary, "http://sap-sp-test.dff.jp/sp.php/ranking/index?user_id=" + user_id+"&display_name=" + display_name + "&photo=" + photo +"&device=android", "post");         
}

对于 PHP 的帖子,我在 javascript 中使用表单 POST

function post(dictionary, url, method) 
        {
            method = method || "post"; // post (set to default) or get

            // Create the form object
            var form = document.createElement("form");
            form.setAttribute("method", method);
            form.setAttribute("action", url);

            // For each key-value pair
            for (key in dictionary) {
                //alert('key: ' + key + ', value:' + dictionary[key]); // debug
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden"); // 'hidden' is the less annoying html data control
                hiddenField.setAttribute("name", key);
                hiddenField.setAttribute("value", dictionary[key]);
                form.appendChild(hiddenField); // append the newly created control to the form
            }

            document.body.appendChild(form); // inject the form object into the body section
            form.submit();
        }

并在 PHP 中接收 json

if($this->_getParam('device') == "android")
        {
            $data = $_POST["jsonData"];
            $data = stripslashes($data);
            $friends = $data;
        }

无论如何,这种方法对我有用,谢谢墨西哥流浪乐队的帮助

于 2012-07-25T06:50:59.907 回答