我最近在java中编写了一些代码,该代码应该将字符串发送到php脚本,它的工作原理非常好。但是当我在android程序中使用它时它拒绝工作。以为有人可以帮我找出问题所在!
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;
}
我确实通过添加
允许清单中的互联网权限 <uses-permission android:name="android.permission.INTERNET" />
但它根本没有给我任何结果。起初我认为也许在PHP脚本中有一些东西丢失了,但是在eclipse中测试它时工作得非常好,所以android部分肯定会出现错误或缺失,对吧?
答案 0 :(得分:1)
确保您的else
块执行。
答案 1 :(得分:0)
这是一个非常糟糕的做法 - 使用Retrofit库来代替使用REST apis。 http://www.vogella.com/tutorials/Retrofit/article.html