2016-09-24 20 views
2

我最近写了一些代码在java应该发送一个字符串到PHP脚本,它工作得很好。但是,当我在android程序中使用它时,它拒绝工作。以为有人可以帮助我找出问题所在!Android的HTML POST不起作用,没有错误

public static String main(String x, String y){ 
    if (android.os.Build.VERSION.SDK_INT > 9) 
    { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
}else{ 

     try{ 

      String username = x; 
      String password = y; 

      URL url = new URL(login_url); 
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
      httpURLConnection.setRequestMethod("POST"); 
      httpURLConnection.setDoInput(true); 
      httpURLConnection.setDoOutput(true); 

      OutputStream outputStream = httpURLConnection.getOutputStream(); 
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 

      String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&" 
        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8"); 

      bufferedWriter.write(post_data); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      outputStream.close(); 

      // LÄSER FRÅN HEMSIDAN 

      InputStream inputStream = httpURLConnection.getInputStream(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")); 
      String result=""; 
      String line=""; 
      while((line = bufferedReader.readLine()) != null){ 

       result += line; 
      } 



      //AVSLUTA CONNECTION 
      bufferedReader.close(); 
      inputStream.close(); 
      httpURLConnection.disconnect(); 

      return result; 

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



    return null; 

} 

我确实允许清单中的Internet权限,加入

<uses-permission android:name="android.permission.INTERNET" /> 

,但它根本没有给我结果。起初我以为可能在PHP脚本中缺少某些东西,但在eclipse中进行测试时它的工作状态非常好,所以在android部件中一定有某些错误或缺失,对吧?

+0

你可以在刷新你的数据并查看你有什么后添加这个'Log.d(“HTTPSENDER”,“”+ httpURLconnection.getResponseCode());''在某些情况下,这也可以解决你的怪异错误。 – user1506104

+0

@ user1506104谢谢,我会给它一个镜头,看看会发生什么! :) – Janono

+0

你有没有得到响应码?它工作? – user1506104

回答

0

这是一个非常糟糕的做法 - 使用Retrofit库来消费REST API。 http://www.vogella.com/tutorials/Retrofit/article.html

+0

是什么让它如此糟糕?即时通讯问,因为我想学习,而不是“保护”我的代码:) – Janono

+0

没有什么'保护' - 你应该为你的网络代码编写测试,或者,在某些情况下可能不清楚,如果某些API不工作或你使用api的代码有一些错误。另一方面,该库已经过测试。 –

相关问题