2014-04-30 171 views
0

我是新的Android我尝试使用JSON发送POST方法到PHP我发送的数据不会出现在PHP中,在PHP中发布请求但是当我尝试读取POST数据时我有数组空值。发送json http post

protected void sendJson(final String username, final String password) { 
     Thread t = new Thread() { 

      public void run() { 
       Looper.prepare(); 
       HttpClient client = new DefaultHttpClient(); 
       HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); 
       HttpResponse response; 
       JSONObject json = new JSONObject(); 
       String URL = "MY_URL"; 

       try { 
         HttpPost post = new HttpPost(URL); 
         json.put("section", "API"); 
         json.put("username", username); 
         json.put("password", password); 
         StringEntity se = new StringEntity(json.toString()); 
         se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
         post.setEntity(se); 
         response = client.execute(post); 

         if(response!=null) 
         { 
          String result = EntityUtils.toString(response.getEntity()); 

          Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); 
          //InputStream in = response.getEntity().getContent(); //Get the data in the entity 
         } 

       } catch(Exception e) { 
        e.printStackTrace(); 
        Toast.makeText(getBaseContext(), "Cannot Estabilish Connection", Toast.LENGTH_LONG).show(); 
       }  
       Looper.loop(); 
      } 
     };  
     t.start();  
    } 
+0

你还需要把字符集。 – sakir

回答

0

尝试accumulate代替put

json.accumulate("section", "API"); 
        json.accumulate("username", username); 
        json.accumulate("password", password); 

试试这个梅索德设置标题:

post.setEntity(se); 

post.setHeader("Accept", "application/json"); 
post.setHeader("Content-type", "application/json"); 

如果你想也也看看到GSON API。它有助于解析...这是一个不错的tuto