Android-将JSONArray发送到php
大家好,我正在尝试将我的JSONArray发送到php页面 我得到了HTTP//1.1200,但我仍然无法在我的php页面中显示它,我仍然不知道我是否成功发送了它 这是我的android代码Android-将JSONArray发送到php,php,android,json,http-post,Php,Android,Json,Http Post,大家好,我正在尝试将我的JSONArray发送到php页面 我得到了HTTP//1.1200,但我仍然无法在我的php页面中显示它,我仍然不知道我是否成功发送了它 这是我的android代码 public void sendJson() { HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.ge
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());
}
}
我已经在这里尝试了一些示例,但仍然无法发送数据
JSON数组(MixiActivity.entry)不是空的
当我尝试使用log打印它时,日志显示JSON数组的正确值
但我就是无法将其发送到PHP
请帮我解决这个问题
非常感谢
Niko您可以尝试在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'};
或
您还可以尝试发出get请求或通过php文件中的$\请求访问数据。
无论您使用什么,都是必需的
或
试试这是一个工作代码。。。它是一个可以直接用于将数据传递到文件的类。使用:静态调用函数,并导入所有必需的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";
}
最后我放弃了android中的http post 现在我正在使用javascript从android获取jsonarray 用这个 公共类JavaScriptInterface{ 语境
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的post,我在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;
}
这个方法对我很有效
无论如何,感谢mariachi的帮助很抱歉,mariachi我已经尝试了这两种方法,但我仍然无法发布JSON数组。还有其他想法吗?感谢您对
response.getStatusLine().toString()的响应
您尝试了我的哪一个建议?我使用了您的第二个建议,它返回HTTP/1.1 200 OK,我也尝试了您的第一个建议,它返回相同的响应,您对此有何看法?很抱歉,mariachi,但您的代码不适合我,我在PHP端使用$json=file\u get\u contents('php://input')$obj=json_decode($json);$name=$obj->{'item0'};echo$json;echo$obj;echo$name;print_r($json);print_r($obj);print_r($name);但是没有打印或回显任何内容。我错过了任何权限吗?谢谢,在我朋友的iphone程序中(还有一个iphone版本)它正在工作,他正在使用一个简单的HTTPpost,就像我在问题中使用的一样
if($this->_getParam('device') == "android")
{
$data = $_POST["jsonData"];
$data = stripslashes($data);
$friends = $data;
}