1.MainActivtiy.java
这里使用官方建议的HttpURLConnection进行连接服务器
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button button;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.connect);
button.setOnClickListener(this);
textView = (TextView)findViewById(R.id.display_content);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.connect:
connectServer();
break;
default:
break;
}
}
private void connectServer(){
new Thread(new Runnable() {
@Override
public void run() {
try {
int c;
StringBuilder string = new StringBuilder();
URL url = new URL("http://192.168.0.88:8000");
的服务器IP,我使用的是Django搭建的简单服务器
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine())!=null){
string.append(line);
}
Log.d("反馈:",string.toString());
showResquesPonse(string.toString());
} catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
private void showResquesPonse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(response);
}
});
}
}
2.布局文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#F00"
android:textAllCaps="false"
android:id="@+id/display_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/connect"
android:text="@string/connect_text"
android:textColor="#FF0"/>
</android.support.constraint.ConstraintLayout>