在android中显示连接的简单代码
php代码地址:http://kardgar.gigfa.com/toosab/connect.php ?i=1
我还添加了 use-permission android:name="android.permission.INTERNET"
和MainActivity.java
public class MainActivity extends AppCompatActivity {
public static String res = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button);
new getcount("http://kardgar.gigfa.com/toosab/connect.php").execute();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext() ,res ,Toast.LENGTH_LONG).show();
}
});
}
}
和 getcount.java
public class getcount extends AsyncTask{
private String Link="";
public getcount(String link ){
Link=link;
}
@Override
protected String doInBackground(Object... arg0) {
try{
String data = "";
URL mylink=new URL(Link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) !=null){
sb.append(line);
}
MainActivity.res = sb.toString();
}catch(Exception ignored){
}
return "";
}
}
当我运行这段代码时,我得到了其他东西
元芳怎么了