我一直在尝试将数据从我的Android应用程序发送到我的服务器。我使用的服务器是EasyPHP。在我的onCreate()函数中,我有:
user_editbox = (EditText) findViewById(R.id.username_id);
phone_editbox = (EditText) findViewById(R.id.phonenum_id);
submit_button = (Button) findViewById(R.id.submit_id);
submit_button.setOnClickListener( new View.OnClickListener() {
String username = "Gina";
String phone_number = "2225550000";
public void onClick(View view)
{
Log.d(TAG, username);
Log.d(TAG, phone_number);
if(username != null && phone_number != null)
{
Log.d(TAG, "Inside " + username);
Log.d(TAG, "Inside " + phone_number);
try {
Log.d(TAG, "Entered try");
URL url = new URL("http://localhost/Web%20/Practice/Android%20Login/phpserver.php");
Log.d(TAG, "URL given");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("Username ", username)
.appendQueryParameter("PhoneNumber ", phone_number );
String query = builder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream(); // <--- Problem
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
urlConnection.connect();
}catch(IOException e)
{
e.printStackTrace();
}
当程序到达
时出现问题 OutputStream os = urlConnection.getOutputStream();
出现一个说明
的对话框 Unfortunately, Program has stopped
我试图通过突出显示的代码了解可能导致程序崩溃的原因。服务器似乎运行顺利,PHP脚本如下所示:
有什么想法吗?
logcat的
07-11 22:17:30.118 2645-2645/com.example.czar.connectingtoserver D/MSG: onCreate
07-11 22:17:30.120 2645-2645/com.example.czar.connectingtoserver D/MSG: onStart
07-11 22:17:30.122 2645-2645/com.example.czar.connectingtoserver D/MSG: onResume
07-11 22:19:24.758 2645-2645/com.example.czar.connectingtoserver D/MSG: Clicked
07-11 22:19:24.758 2645-2645/com.example.czar.connectingtoserver D/MSG: Gina
07-11 22:19:24.758 2645-2645/com.example.czar.connectingtoserver D/MSG: 2225550000
07-11 22:19:24.759 2645-2645/com.example.czar.connectingtoserver D/MSG: Inside Gina
07-11 22:19:24.759 2645-2645/com.example.czar.connectingtoserver D/MSG: Inside 2225550000
07-11 22:19:24.759 2645-2645/com.example.czar.connectingtoserver D/MSG: Entered try
07-11 22:19:24.759 2645-2645/com.example.czar.connectingtoserver D/MSG: URL given
07-11 22:19:24.759 2645-2645/com.example.czar.connectingtoserver D/MSG: Output set to true
07-11 22:19:24.759 2645-2645/com.example.czar.connectingtoserver D/MSG: String Encoded
答案 0 :(得分:0)
崩溃,因为这里有NetworkOnMainThreadException
。您需要将HttpURLConnection
的所有工作都放到Thread
。