2011-07-20 134 views
0

我用httppost從Android發送JSON對象到我的PHP文件我的Java代碼Android的JSON解析

JSONObject json = new JSONObject(); 
    try 
    { 
     json.put("email", "15"); 

    } 
    catch (JSONException e) 
    { 

     e.printStackTrace(); 
    } 
    String url = "http://xxxx.in/xxx/xxx.php"; 
    HttpResponse re; 
    String temp = new String(); 
    try 
    { 
     re = HTTPPoster.doPost(url, json); 
     temp = EntityUtils.toString(re.getEntity()); 
     Log.d("Main",temp); 
    } 
    catch (ClientProtocolException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    if (temp.compareTo("SUCCESS")==0) 
    { 
     Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); 
    } 

    public class HTTPPoster 
{ 
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost request = new HttpPost(url); 
    HttpEntity entity; 
    StringEntity s = new StringEntity(c.toString()); 

    s.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
    entity = s; 
    request.setEntity(entity); 
    HttpResponse response; 
    response = httpclient.execute(request); 
    return response; 
} 
} 

和我的PHP代碼

$data = json_decode($_POST['json']); 
echo $data['email']; 
echo "working"; 

唯一工作是ecohed回我不得到$數據[ '電子郵件']內容

回答

2

How to post JSON to PHP with curl

使用file_get_contents('php://input');代替$_POST['json']

+0

我試過你說的但它不工作... –

+0

你試過'$ data = json_decode(file_get_contents('php:// input'));'?如果不工作,試試這兩個(我的和jamapag的)答案'$ data = json_decode(file_get_contents('php:// input')); echo $ data-> email;' – Selvin

+0

好的,謝謝.... –

1

您創建的JSONObject不JsonArray,所以儘量:

echo $data->email; 
+0

我想什麼ü告訴,但其不工作... –

+0

你嘗試'的var_dump($數據)'?另請嘗試@ Selvin的解決方案。 – jamapag

+0

好的,謝謝...... –