2015-06-13 45 views
0

任何想法为什么这不是发布任何数据?所有我从我的PHP页面$_POST得到的是array(0){}或换句话说没有在$_POSTgetData()是一个充满数据的字符串。我正尝试从已弃用的DefaultHttpClient切换。Android的HttpURLConnection似乎没有发布?

HttpURLConnection conn = null; 
      try { 
       URL u = new URL(url); 
       conn = (HttpURLConnection) u.openConnection(); 
       conn.setDoOutput(true); 
       conn.setDoInput(true); 
       conn.setChunkedStreamingMode(0); 
       conn.setConnectTimeout(10000); 
       conn.setReadTimeout(10000); 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       //conn.setRequestProperty("Content-Type","application/json"); 
       conn.getOutputStream().write(getData().getBytes("UTF-8")); 
       conn.connect(); 

       InputStream content = new BufferedInputStream(conn.getInputStream()); 
       BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); 
       String s = ""; 
       while ((s = buffer.readLine()) != null) { 
        builder.append(s + "\n"); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       conn.disconnect(); 
      } 
+0

尝试添加'conn.getOutputStream()的flush();''之前conn.connect();'。 – Salem

+0

还没有发布。 – Ael

回答

0

最好的办法是 - >>

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> { 


protected void onPreExecute() { 
    super.onPreExecute(); 
    dialogOff.setMessage("Loading Data.."); 

} 
protected Boolean doInBackground(String... urls) { 


    try { 

     HttpGet httppost = new HttpGet(urls[0]); 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpResponse response = httpclient.execute(httppost); 

     // StatusLine stat = response.getStatusLine(); 
     int status = response.getStatusLine().getStatusCode(); 

     if (status == 200) { 
      HttpEntity entity = response.getEntity(); 
      String data = EntityUtils.toString(entity); 

      data=new String(data.getBytes("ISO-8859-1"), "UTF-8"); 

      JSONArray jarray = new JSONArray(data); 
      LatLng point; 

      for (int i = 0; i < jarray.length(); i++) 
       JSONObject object = jarray.getJSONObject(i); 




      return true; 
     } 



    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 



    return false; 
} 
protected void onPostExecute(Boolean result) { 


    if(result) 
     Toast.makeText(getApplicationContext(), "Data transfered Successfully", Toast.LENGTH_LONG).show(); 
    else{ 
     Toast.makeText(getApplicationContext(), "Unable to fetch from server", Toast.LENGTH_LONG).show(); 
     dialogOff.cancel(); 
    } 



} 

}

+0

我试图从'DefaultHttpClient'切换,因为它在API 22之后被删除,并且他们说效率不高: - 客户端 – Ael

+0

我的应用程序运行完美,超级快速的方法..有时更好地使用你认为更好,更简单! –

+0

非常真实。感谢您的提醒。可以将DefaultHttpClient读入新API(请参阅链接)。这是我的主要原因。因为它被删除。 – Ael