我最近写了一些代码在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部件中一定有某些错误或缺失,对吧?
你可以在刷新你的数据并查看你有什么后添加这个'Log.d(“HTTPSENDER”,“”+ httpURLconnection.getResponseCode());''在某些情况下,这也可以解决你的怪异错误。 – user1506104
@ user1506104谢谢,我会给它一个镜头,看看会发生什么! :) – Janono
你有没有得到响应码?它工作? – user1506104