2016-12-25 30 views
1

我正在開發一個android應用程序,它向服務器發送一個http get/post請求並以字符串的形式接收響應。服務器使用php來檢索get/post請求。在android應用程序和php服務器中使用http get/post請求時出現文本編碼錯誤?

http://amazinginside.esy.es/devolopment.php?name=Sangeeth

這是我的要求。而我的OnCreate()的實現是

public class MainActivity extends Activity 
{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     ServerConnect s=new ServerConnect(); 
     try 
     { 
      String[] params={"name","Sangeeth"}; 
      String request=s.Get("http://amazinginside.esy.es/devolopment.php",params); 
      TextView textView=(TextView)findViewById(R.id.mytext); 
      textView.setText(request); 
     } 
     catch(ExecutionException e) 
     { 
      //Exception handling 
     } 
     catch (InterruptedException e) 
     { 
      //Exception handling 
     } 
    } 
} 

下面是服務器連接類

public class ServerConnect 
{ 

    public static String Get(String s ,String[] a) throws ExecutionException, InterruptedException { 

     String parameters = ""; 

     for (int i = 0; i < a.length; i++) { 
      try { 
       parameters += a[i] + "=" + URLEncoder.encode(a[i + 1], "UTF-8") + "&"; 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      i++; 
     } 
     return new DownloadWebpageTask().execute(s+"?"+parameters,"GET","").get(); 
    } 

    public static String Post(String s ,String[] a) throws ExecutionException, InterruptedException { 

     String parameters =""; 

     for(int i=0; i<a.length ;i++){ 
      try { 
       parameters += a[i]+"=" + URLEncoder.encode(a[i+1],"UTF-8")+"&"; 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      i++; 
     } 


     return new DownloadWebpageTask().execute(s,"POST",parameters).get(); 

    } 

    private static class DownloadWebpageTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 

// params comes from the execute() call: params[0] is the url. 
      try { 
       return downloadUrl(urls[0] ,urls[1],urls[2]); 
      } catch (IOException e) { 
       return "Unable to retrieve web page. URL may be invalid."; 
      } 
     } 

     // onPostExecute displays the results of the AsyncTask. 
     @Override 
     protected void onPostExecute(String result) { 
     } 

     private String downloadUrl(String myurl ,String method , String data) throws IOException { 
      InputStream is = null; 
// Only display the first 500 characters of the retrieved 
// web page content. 


      try { 
       URL url = new URL(myurl); 
       HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(10000 /* milliseconds */); 
       conn.setConnectTimeout(15000 /* milliseconds */); 
       conn.setRequestMethod(method); 
       conn.setDoInput(true); 
       conn.setRequestProperty("Accept-Encoding", "gzip"); 
       conn.setRequestProperty("Connection", "close"); 
       if (method == "POST") { 
        conn.setDoOutput(true); 

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

        PrintWriter out = new PrintWriter(conn.getOutputStream()); 
        out.print(data); 
        out.close(); 
       } 
       // Starts the query 
       conn.connect(); 
       int response = conn.getResponseCode(); 
       is = conn.getInputStream(); 

       // Convert the InputStream into a string 


       String contentAsString = readIt(is, conn.getContentLength()); 
       return contentAsString; 


       // Makes sure that the InputStream is closed after the app is 
       // finished using it. 
      } finally { 
       if (is != null) { 
        is.close(); 
       } 
      } 
     } 

     private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { 
      int n = 0; 
      char[] buffer = new char[1024 * 4]; 
      InputStreamReader reader = new InputStreamReader(stream, "UTF8"); 
      StringWriter writer = new StringWriter(); 
      while (-1 != (n = reader.read(buffer))) writer.write(buffer, 0, n); 
      return writer.toString(); 
     } 


    } 

這纔是我的PHP服務器腳本

<?php 
    header('Content-Type: text/html; charset=utf-8'); 
    if($_GET["name"]) 
    { 
     echo "Server responded : ".$_GET["name"]; 
    } 
    else 
    { 
     echo "Server revoked"; 
    } 
    ?> 

在使用谷歌Chrome或IE或邊緣,我完美地獲得結果。但是,當我使用我的應用程序來請求服務器時,我得到的迴應是,但它是不可讀的。可能是編碼不匹配。但是當我使用本地主機(我正在使用WampServer)時,我也在應用中獲得了可讀的響應。 請參閱:IMAGE OF WHAT IM GETTING 我的代碼或服務器腳本有問題嗎?有什麼建議麼?

回答

0

您試圖將請求設置爲textview而不是響應。

try 
     { 
      String[] params={"name","Sangeeth"}; 
      String request=s.Get("http://amazinginside.esy.es/devolopment.php",params); 
      TextView textView=(TextView)findViewById(R.id.mytext); 
    =======> textView.setText(request); 
     } 

將異步請求發送到服務器後,將textview設置爲在異步任務的postExecute函數中收到的響應。

 //onPostExecute displays the results of the AsyncTask. 
     @Override 
     protected void onPostExecute(String result) { 
      (yourInstanceOfTextView).setText(result); 
     } 

和更好的方式來建立的URI是使用URI類和URI.Builder

+0

沒辦法,我已經實現了我的TextView實例內onPostExecute(),但仍得到一個野生編碼字符串 –

+0

我發現我現在的答案。這是由我的下載url函數中多餘的2行引起的。 –

相關問題