我遇到了问题。
我无法弄清楚为什么以下代码无效。
这是一个简单的应用程序,它向一些应该在表中插入行的php片段发送GET请求。
我无法理解为什么它不起作用。
请帮忙。
的java:
package com.example.michael.biyum;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
final AlertDialog alertDialog = alertDialogBuilder.create();
Button startBtn = (Button) findViewById(R.id.btn);
final TextView t = (TextView) findViewById(R.id.hello);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
Toast.makeText(getApplicationContext(),"GET:"+current,Toast.LENGTH_LONG).show();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
});
}
}
PHP:
<?php
require('connect.inc.php');
$update_offline="INSERT INTO offline_waiters (user_partner,mail,chat_room) VALUES(0,'gavno','gavno')";
$query_run= mysqli_query($conn,$update_offline);
echo "new";
?>
这是一个简单的测试,应该在我的表格中输入一个新行。
当我通过浏览器手动制作请求时,它可以正常工作。
再次请帮助我了解问题所在。
答案 0 :(得分:1)
您需要从主线程中获取网络操作。
我刚刚开始使用AsyncTask进行测试:
class MyAsyncTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
StringBuilder result = new StringBuilder();
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
result.append(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),"GET:"+result,Toast.LENGTH_LONG).show();
}
}
只需从点击监听器执行AsyncTask:
startBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
new MyAsyncTask().execute();
});
吐司中的结果: