2012-08-02 78 views
2

我有一個Android應用程序與託管服務提供商上的服務器通信。 此應用程序發送一個http請求php腳本檢索請求並在數據庫中執行操作。 我改變了數據庫,我修改了程序,現在我在服務器上發現錯誤:「您的請求超時,請重試請求。」錯誤:「您的請求超時,請重試請求。」與Android和PHP程序

當我在firefox或chrome等瀏覽器中執行命令http時,命令執行正確,通過防止執行代碼時發生錯誤。

這不是腳本或http請求,因此我根本沒有看到可能發生的情況。你可以幫我嗎?非常感謝你。

有Android的代碼:

public class ConnexionSQL extends AsyncTask<Object,Void, ArrayList<String[]> > { 


private static ArrayList<String[]> lesMessagesEtDate; 
private String mydataFromHMI; 
private String myFichierPHPbase; 
private ProgressDialog pd; 
private String[] splitData; 
private boolean isProblemConnexion; 

public ConnexionSQL(Activity activity) { 

    pd = new ProgressDialog(activity); 
    lesMessagesEtDate = new ArrayList<String[]>(); 
    mydataFromHMI = ""; 
    myFichierPHPbase=""; 
    isProblemConnexion = false; 
} 


protected ArrayList<String[]> doInBackground(Object... parametres) { 
    Object[] tabArg = parametres; 
    ArrayList<String[]> messagesDateEtLocalisation = new ArrayList<String[]>(); 
    pd.show(); 

    if (((String)tabArg[3]).equalsIgnoreCase("insert")){ 

     insertIntoBD((String)tabArg[0], (Context)tabArg[1], (String)tabArg[2]); 

    }else if(((String)tabArg[3]).equalsIgnoreCase("connect")){ 

     messagesDateEtLocalisation = ConnexionBD((String)tabArg[0], (Context)tabArg[1], (String)tabArg[2]); 
    } 
    return messagesDateEtLocalisation; 
} 


protected void onPreExecute() { 
    pd.setMessage("Chargement en cours"); 
    pd.show(); 
} 


protected void onProgressUpdate(){ 
    pd.setMessage("Chargement en cours"); 
    pd.show(); 
} 

protected void onPostExecute(ArrayList<String[]> array) 
{ 
    pd.setMessage("Le chargement se termine"); 
    pd.dismiss();  

} 

public void insertIntoBD(String dataFromHMI, Context context, String FichierPHPbase){ 


    mydataFromHMI = dataFromHMI; 
    myFichierPHPbase = FichierPHPbase; 



    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

    try{ 
     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 
     HttpProtocolParams.setUseExpectContinue(params, false); 
     HttpConnectionParams.setConnectionTimeout(params, 10000); 
     HttpConnectionParams.setSoTimeout(params, 10000); 
     ConnManagerParams.setMaxTotalConnections(params, 1000); 
     ConnManagerParams.setTimeout(params, 30000); 

     SchemeRegistry registry = new SchemeRegistry(); 
     registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(), 80)); 
     registry.register(new Scheme("https",PlainSocketFactory.getSocketFactory(), 80)); 
     ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); 
     HttpClient httpclient = new DefaultHttpClient(manager, params); 

     HttpPost httppost = new HttpPost("http://routeslibre.fr/"+ myFichierPHPbase + "?variable=" + mydataFromHMI); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     httpclient.execute(httppost); 


    } 
    catch(Exception e){ 
     Log.i("taghttppost",""+e.toString()); 
     isProblemConnexion = true; 
    } 

} 



public ArrayList<String[]> ConnexionBD(String dataFromHMI, Context context,String FichierPHPbase) { 

    mydataFromHMI = dataFromHMI; 
    myFichierPHPbase = FichierPHPbase; 

    String result = null; 
    InputStream is = null; 
    JSONObject json_data=null; 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

    try{ 
     //commandes httpClient 

     HttpParams params = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 
     HttpProtocolParams.setUseExpectContinue(params, false); 
     HttpConnectionParams.setConnectionTimeout(params, 10000); 
     HttpConnectionParams.setSoTimeout(params, 10000); 
     ConnManagerParams.setMaxTotalConnections(params, 1000); 
     ConnManagerParams.setTimeout(params, 30000); 

     SchemeRegistry registry = new SchemeRegistry(); 
     registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(), 80)); 
     registry.register(new Scheme("https",PlainSocketFactory.getSocketFactory(), 80)); 
     ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); 


     HttpClient httpclient = new DefaultHttpClient(manager, params);    

     GestionStrings gestionString = new GestionStrings(); 
     splitData = mydataFromHMI.split(";;;"); 
     mydataFromHMI = gestionString.blancTraitement(splitData[0]) 
       + ";;;" 
       + gestionString.blancTraitement(splitData[1]) 
       + ";;;"; 

     HttpPost httppost = new HttpPost("http://routeslibre.fr/"+ myFichierPHPbase + "?variable=" + mydataFromHMI); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
    } 
    catch(Exception e){ 
     Log.i("taghttppost",""+e.toString()); 
     isProblemConnexion = true; 
    } 


    //conversion de la réponse en chaine de caractère 
    try 
    { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); 

     StringBuilder sb = new StringBuilder(); 

     String line = null; 

     while ((line = reader.readLine()) != null) 
     { 
      sb.append(line + "\n"); 
     } 

     is.close(); 

     result = sb.toString(); 
     if (result.startsWith("<html>")) 
     { 
      isProblemConnexion = true; 
     } 
    } 
    catch(Exception e) 
    { 
     Log.i("tagconvertstr",""+e.toString()); 
     isProblemConnexion = true; 
    } 
    //recuperation des donnees json 
    try{ 
     JSONArray jArray = new JSONArray(result); 

     for(int i=0;i<jArray.length();i++) 
     { 

      json_data = jArray.getJSONObject(i); 
      String[] messageEtDate = new String[2]; 
      messageEtDate[0] = json_data.getString("message"); 
      messageEtDate[1] = json_data.getString("date"); 
      lesMessagesEtDate.add(messageEtDate); 


     } 
     //setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, lesMessages)); 
    } 
    catch(JSONException e){ 
     Log.i("tagjsonexp",""+e.toString()); 
     isProblemConnexion = true; 
    } catch (ParseException e) { 
     Log.i("tagjsonpars",""+e.toString()); 
     isProblemConnexion = true; 
    } 
    if (isProblemConnexion){ 

     lesMessagesEtDate = new ArrayList<String[]>(); 
     lesMessagesEtDate.add(new String[]{"connexion_error_1234"}); 
     isProblemConnexion = false; 
    } 
    return lesMessagesEtDate; 
} 

}

有PHP腳本代碼:

$base = mysql_connect ('sql31.free-h.org:3306', '*****', '******'); 
mysql_select_db ('routeslibre', $base) ; 
$variable = $_GET['variable']; 
$first_token = strtok($variable, ";;;"); 
$second_token = strtok(";;;"); 
$req =mysql_query("SELECT message, date from routeslibre.routeslibre where departement='$first_token' AND  voie='$second_token' ORDER BY date"); 
$output=array(); 
while ($row=mysql_fetch_array($req)) {  
$output[]=$row;  
} 
//on encode en JSON 
print(json_encode($output)); 
mysql_free_result ($req); 

當我停止就行調試器 「is.close();」值「db」等於「<html> Your request timed out. Please retry the request

如果你不介意,你可以給我一個技巧,找到錯誤的方法嗎?

我,就把這行代碼: int test = response.getStatusLine().getStatusCode(); 和測試值是408左右(如在網站所描述)的平均值我在託管服務提供商有一個錯誤。但是爲什麼當我把http請求,從代碼retreived:值http://routeslibre.fr/"+ myFichierPHPbase + "?variable=" + mydataFromHMI,當我把它放在一個Web客戶端作爲鉻或Firefox,我的PHP腳本工作非常發現......我不明白....? ?

回答

0

有了這段代碼,那並不完美:有時候它的工作有時候不行。當調試器在執行操作中設置時,將出現異常,其值僅爲「null」。你可以幫幫我嗎 ?

這裏是一個不工作找到代碼:

HttpGet httpGet = new HttpGet(url); 
HttpParams httpParameters = new BasicHttpParams(); 
// Set the timeout in milliseconds until a connection is established. 
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000; 
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data. 
int timeoutSocket = 5000; 
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 
HttpResponse response = httpClient.execute(httpGet); 

我找到了一個解決方案,我遍歷,直到我有一個請求(狀態從服務器retreived等於200)或執行代碼,如果請求沒有提供任何結果,則會啓動錯誤。 這裏有我的解決方案:

 String httpRequest = new String("http://routeslibre.fr/"+ myFichierPHPbase + "?variable=" + mydataFromHMI); 
     HttpPost request = new HttpPost(httpRequest); 
     HttpParams httpParameters = new BasicHttpParams(); 
     HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); 
     HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); 

     DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); 

     HttpResponse response = null; 
     for(int i= 0; i < 30; i++){ 
      response = httpclient.execute(request); 
      if (response.getStatusLine().getStatusCode() == 200){ 
       break; 
      }else if (i == 29){ 

       //ERROR CODE 
      } 
     }