【达内课程】网络通信之HTTP协议(2)
程序员文章站
2022-03-28 11:12:11
...
如何使用Android代码发送HTTP POST请求
1、创建URL对象
URL url = new URL("http://xxx");
2、创建HttpURLConnection对象
conn = url.openConnection()
3、设置消息方式和消息头
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
(multipart/form-date)
4、设置开启输出流
使用输出流输出请求参数
conn.setDoOutput(true);
os = conn.getOutputStream();
os.write("date=2016&number=00001".getBytes());
os.flush();
5、调用conn.getInputStream()发送请求并获取响应
is = conn.getInputStream()
6、解析响应数据,获取响应文本
is转换为String
在上一节的栗子上修改为POST
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_connect;
private EditText et_date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViews();
}
private void setViews() {
et_date = findViewById(R.id.et_date);
btn_connect = findViewById(R.id.btn_connect);
btn_connect.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_connect:
new Thread(){
@Override
public void run() {
try {
findFlightsByPost();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
break;
}
}
//使用Get方式发送请求 获取航班数据
private void findFlightsByPost() throws IOException {
//1、URL
URL url = new URL("http://192.168.3.25:8888/android_jsp/flight_index.jsp");
//2、HttpURLConnection
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//3、setRequestMethod() setRequestProperty()
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//4、doOutput(true)
conn.setDoOutput(true);
String d = et_date.getText().toString();
String param = "date="+d;
OutputStream os = conn.getOutputStream();
os.write(param.getBytes("utf-8"));
os.flush();
//5、conn.InputStream
InputStream is = conn.getInputStream();
//6、is转成String
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line=reader.readLine())!=null){
sb.append(line);
}
Log.d("info",sb.toString());
}
}
Json
栗子:登录
首先,查看接口文档
增加权限
<uses-permission android:name="android.permission.INTERNET" />
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_add;
private EditText et_number;
private EditText et_password;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case ADD_CARD_SUCCESS:
Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
break;
case ADD_CARD_FAIL:
Toast.makeText(MainActivity.this,"登录失败:"+msg.obj,Toast.LENGTH_SHORT).show();
break;
}
}
};
public static final int ADD_CARD_SUCCESS = 1;
public static final int ADD_CARD_FAIL = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViews();
}
private void setViews() {
et_number = findViewById(R.id.et_number);
et_password = findViewById(R.id.et_password);
btn_add = findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_add:
new Thread(){
@Override
public void run() {
try {
addCard();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
break;
}
}
private void addCard() throws IOException, JSONException {
//1、URL
URL url = new URL("http://域名/site/login");
//2、HttpURLConnection
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//3、setRequestMethod setRequestProperty()
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//4、doOutPut
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
//5、构建参数
String user_name = et_number.getText().toString();
String password = et_password.getText().toString();
String param = "user_name="+user_name+"&password="+password;
os.write(param.getBytes("utf-8"));
os.flush();
//6、inputStream
InputStream is = conn.getInputStream();
//7、is转换成String
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine())!=null){
sb.append(line);
}
String json = sb.toString();
//7、解析json
JSONObject obj = new JSONObject(json);
String res = obj.getString("code");
//8、发消息给Handler
if(res.equals("0")){
//成功
handler.sendEmptyMessage(ADD_CARD_SUCCESS);
}else{
//失败
Message msg = new Message();
msg.what = ADD_CARD_FAIL;
msg.obj = obj.getString("message");
handler.sendMessage(msg);
}
}
}
上一篇: 沙田村屋
下一篇: 浅析多个单列索引和联合索引的区别