Android中与服务器通信

时间:2022-03-02 17:18:47

    服务器开发语言我选择的是php

    服务器搭建完成之后,在服务器www目录下写一个demo.php,php的代码如下:

   <?php
    if($_POST['username'] == "admin"){
        echo "admin";
    }else{
        echo "user";
    }
?>

  然后在安卓中向该服务器发送请求:

 

public class http extends AppCompatActivity {

HttpUtil httpUtil;
TextView textView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
httpUtil = new HttpUtil();
Button button = (Button)findViewById(R.id.send);
textView = (TextView)findViewById(R.id.text3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String str = httpUtil.sendHttpRequest("http://115.159.217.226/demo.php");
textView.setText(str);
}
});
}
}
先写一个http类,调用我自己写的sendHttpRequest();方法

方法的代码如下:
public class HttpUtil {
private OkHttpClient client;
private Request request;
private Response response;
public String str;
public String sendHttpRequest(final String address){
new Thread(new Runnable() {
String responseData;
public void run() {
try{
client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("username","admin")
.build();
request = new Request.Builder()
.url(address)
.post(requestBody)
.build();
response = client.newCall(request).execute();
responseData = response.body().string();
str = responseData;
}catch (Exception e){
e.printStackTrace();

}
}
}).start();
return str;
}
}
最后得到数据为admin,向php服务器通信成功