2015-11-06 4 views
0

Я пытаюсь подключить свой проект андроида к странице PHP, но он не работает, что такое ошибка, я не знаю, почему она не работает для меня, я устанавливаю разрешение на интернетсписок данных не указан

это код сайта, где это проверить соединение HTTP:

public class site { 
     static String response = null; 
     public final static int getrequest =1; 
     public final static int postrequest=2; 
     public site(){} 
     public String histosite (String url, int requestmothod){ 
      return this.histosite(url,requestmothod); 
     } 
     public String histosite(String urlsddress, int requestmothod,HashMap<String,String> params){ 
      URL url; 
      String response= ""; 
      try { 
       url= new URL(urlsddress); 
       HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(15001); 
       conn.setConnectTimeout(15001); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 
       if (requestmothod == postrequest){ 
        conn.setRequestMethod("POST"); 
       } else if(requestmothod == getrequest){ 
        conn.setRequestMethod("GETRequest"); 
       } 
       if(params != null){ 
        OutputStream ostream = conn.getOutputStream(); 
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ostream,"UTF-8")); 
        StringBuilder requestresult = new StringBuilder(); 
        boolean first = true; 
        for (Map.Entry<String, String> entry: params.entrySet()){ 
         if (first) 
          first=false; 
         else 
          requestresult.append("&"); 
         requestresult.append(URLEncoder.encode(entry.getKey(),"UTF-8")); 
         requestresult.append("="); 
         requestresult.append(URLEncoder.encode(entry.getValue(),"UTF-8")); 
        } 
        writer.write(requestresult.toString()); 
        writer.flush(); 
        writer.close(); 
        ostream.close(); 
       } 
       int reqresponsecode= conn.getResponseCode(); 
       if(reqresponsecode == HttpURLConnection.HTTP_OK){ 
        String line; 
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        while ((line = br.readLine())!= null){ 
         response += line; 
        } 
       } else { 
        response = ""; 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      return response; 
     } 


    } 

это где данные должны извлекаться и представлены:

public class Historical_Sites extends ListActivity { 
    private static final String url= "http://tourin.esy.es/php/historical.php"; 
    private static final String TAG_POSTS="posts"; 
    private static final String TAG_SITE_NAME = "Site_Name"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.ex); 
     new getsite().execute(); 
    } 
    private class getsite extends AsyncTask<Void,Void,Void>{ 
     ArrayList<HashMap<String,String>> siteslist; 
     ProgressDialog prodialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      prodialog= new ProgressDialog(Historical_Sites.this); 
      prodialog.setMessage("Please waite"); 
      prodialog.setCancelable(false); 
      prodialog.show(); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      site Site = new site(); 
      String jsonstr = Site.histosite(url,site.getrequest); 
      Log.d("Response : ", ">" + jsonstr); 
      siteslist= ParseJSON(jsonstr); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void requestres) { 
      super.onPostExecute(requestres); 
      if(prodialog.isShowing()) 
       prodialog.dismiss(); 
      ListAdapter adapter = new SimpleAdapter(Historical_Sites.this,siteslist,R.layout.list, 
        new String[]{TAG_SITE_NAME},new int[]{R.id.lis}); 
      setListAdapter(adapter); 

     } 
     private ArrayList<HashMap<String,String>> ParseJSON(String json){ 
      if(json != null){ 
       try { 
        ArrayList<HashMap<String,String>> SiteList = new ArrayList<HashMap<String,String>>(); 
        JSONObject Jsonobj= new JSONObject(json); 
        JSONArray HistoricalSites = Jsonobj.getJSONArray(TAG_POSTS); 
        for(int i=0 ; i<HistoricalSites.length();i++){ 
         JSONObject c = HistoricalSites.getJSONObject(i); 
         String sitename = c.getString(TAG_SITE_NAME); 
         HashMap<String,String>HistoricalSite = new HashMap<String,String>(); 
         HistoricalSite.put(TAG_SITE_NAME,sitename); 
         siteslist.add(HistoricalSite); 

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


      }else{ 
       Log.e("Service Handeller","No data recieved "); 

      } 
      return null; 
     } 
    } 
} 

этого JSON код:

{"success":1,"message":"Post Available!","posts":[{"Site_Name":"Bahrain National Museum"},{"Site_Name":"Qalat al Bahrain site and museum"},{"Site_Name":"Boats Trips to Bu Maher Fort"},{"Site_Name":"Old Houses of Muharraq"},{"Site_Name":"Bait al Quran"},{"Site_Name":"Al Khamis Mosque"},{"Site_Name":"Arad Fort"},{"Site_Name":"Sheikh Salman Bin Ahmed Al Fateh Fort"},{"Site_Name":"Siyadi House"},{"Site_Name":"Siyadi Mosque"},{"Site_Name":"Al Jasra House"},{"Site_Name":"Al Jasra Handicrafts Centre"},{"Site_Name":"Al Fateh Mosque"},{"Site_Name":"Saar Settlement"},{"Site_Name":"Barbar Temples"}]} 
+0

взгляд на эту http://androidexample.com/Restful_Webservice_Call_And_Get_And_Parse_JSON_Data-_Android_Example/index.php?view=article_discription&aid=101&aaid=123 –

+0

этот пример не использует HttpURLConnection является метод использования, который не поддерживается андроидной студией сейчас – menna

+0

conn.connect(); отсутствует в коде ur –

ответ

0

Используйте этот код

String getWebServiceTask(String requestURL,JSONObject postDataParams,String PostType) 
{ 
    URL url; 
    String response = ""; 
    int responseCode = 0; 
    JSONObject responseObject = null; 
    try { 
     url = new URL(requestURL); 

     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(1500000); 
     conn.setConnectTimeout(1500000); 

     conn.setRequestProperty("Content-Type", "application/json"); 
     conn.setRequestProperty("Accept", "application/json"); 
     conn.setRequestProperty("Content-Language", "en-US,en;q=0.8"); 
     conn.setRequestMethod(PostType); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 
     conn.connect(); 

     if(postDataParams != null){ 
      OutputStream os = conn.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      writer.write(postDataParams.toString()); 
      writer.flush(); 
      writer.close(); 
      os.close(); 
     } 

     responseCode=conn.getResponseCode(); 

     if (responseCode == HttpsURLConnection.HTTP_OK) { 
      String line; 
      BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      while ((line=br.readLine()) != null) { 
       response+=line; 
      } 
     } 
     else { 
      response=""; 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    try { 
     responseObject=new JSONObject(); 
     responseObject.put(AppConstants.API_RESPONSE_CODE, responseCode); 
     responseObject.put(AppConstants.API_RESPONSE, response); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 

    return responseObject.toString(); 
} 
+0

что AppConstants.API_RESPONSE_CODE означает – menna

+0

AppConstants.API_RESPONSE_CODE заменить на «ResponseCode» и AppConstants.API_RESPONSE с помощью «Response» –

Смежные вопросы