HttpURlConnection
用来发送HTTP请求和获取HTTP响应,由于该类时抽象类,不能直接实例化对象,则需要使用URL的openConnection()方法来获取,
URL url = new URL("http://www.mingribook.com/")
HttpURLConnection urlConnection = (HttpURLConnectin) url.openConnection();
int getResponseCode() | 获取服务器的响应代码 |
String getResponseMessage() | 获取服务器的响应消息 |
String getRequestMethod() | 获取发送请求的方法 |
void setRequestMethod(string method) | 设置发送请求方法 |
1.发送GET请求
默认发送的就是GET请求 只需要在指定请求地址通过?参数名=参数值的形式
实列 使用GET方式发表并显示微博信息
AndroidManifesfest.xml
<uses-permission android:name="android.permission.INTERNET" />
package com.example.testapplication;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class GetMethodActivity extends ApplicationActivity{
private EditText content;
private Handler handler; // 定义一个Android.os.Handler对象
private String result;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getmethod);
// 获取输入文本内容EditText组件
content = (EditText)findViewById(R.id.get_content);
// 获取显示结果的TextView组件
final TextView resultTV = (TextView)findViewById(R.id.result);
Button getBtn = (Button) findViewById(R.id.getbtn);
// 点击事件 实现读取服务器信息
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 判断输入内容是否为空,为空给出提示消息,否则访问服务器
if("".equals(content.getText().toString())){
Toast.makeText(GetMethodActivity.this, "请输入要发表的内容", Toast.LENGTH_SHORT).show();
return;
}
handler = new Handler(){ // 将服务器中的数据,显示在UI界面中
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
if(result != null){ // 如果服务器返回结果不为空
resultTV.setText(result); // 显示获取的结果
content.setText(""); // 清空文本框
}
}
};
new Thread(new Runnable() { // 创建一个新线程,用于发送并读取信息
@Override
public void run() {
send(); // 调用send() 方法,用于发送文本内容到web服务器
Message m = handler.obtainMessage(); // 获取一个Message
handler.sendMessage(m); // 发送消息
}
}).start(); // 开启线程
}
});
}
// 创建Base64() 方法 对传递的参数进行Base64编码,用于解决乱码问题
public String base64(String content){ // 对字符串进行Base64编码
try {
// 对字符进行Base64编码
content = Base64.encodeToString(content.getBytes("utf-8"),Base64.DEFAULT);
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
return content;
}
public void send(){
String target = "";
target = "http://192.168.0.105:8080/example/get.jsp?content="
+ base64(content.getText().toString().trim()); // 请求的地址
URL url;
try {
url = new URL(target);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 创建一个HTTP连接
InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 读取内容
BufferedReader buffer = new BufferedReader(in); // 获取输入流对象
String inputLine = null;
// 通过循环逐行读取输入流中的内容
while ((inputLine = buffer.readLine()) != null){
result += inputLine + "\n";
}
in.close(); // 关闭字符输入流对象
urlConn.disconnect(); // 断开连接
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/get"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--输入要发表的内容-->
<EditText
android:id="@+id/get_content"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="@null"
android:hint="输入想要发表的内容~~~~"
/>
<Button
android:id="@+id/getbtn"
android:layout_width="300dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="100dp"
android:background="#4D9DE3"
android:text="发表"
/>
<ScrollView
android:layout_width="280dp"
android:layout_height="240dp"
android:layout_gravity="center_horizontal"
>
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
使用POST方式登录QQ
package com.example.testapplication;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class PostMethodActivity extends ApplicationActivity{
private EditText edit_Username;
private EditText edit_Password;
private Handler handler;
private String result = "";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
edit_Username = (EditText) findViewById(R.id.username);
edit_Password = (EditText) findViewById(R.id.password);
Button login = (Button) findViewById(R.id.login);
// 登录事件 发送信息与服务器交互
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 当用户名,密码为空时相应提示
if("".equals(edit_Username.getText().toString())
|| "".equals(edit_Password.getText().toString())){
Toast.makeText(PostMethodActivity.this, "请填写账号或密码", Toast.LENGTH_SHORT).show();
return;
}
// todo 如何调试psot请求
handler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
// 如果服务器返回值为 ok 则表示账号和密码输入正确
if("ok".equals(result)){
// 登录成功
Toast.makeText(PostMethodActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(PostMethodActivity.this, "请填写正确的账号和密码", Toast.LENGTH_SHORT).show();
}
}
};
new Thread(new Runnable() { // 创建一个新线程,用于从网络上获取数据
@Override
public void run() {
send();
Message m = handler.obtainMessage();
handler.sendMessage(m);
}
}).start();
}
});
}
public void send() {
String target = "http://192.168.0.105:8080//example/post.jsp";//要提交的服务器地址
URL url;
try {
url = new URL(target); //创建URL对象
//创建一个HTTP连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST"); //指定使用POST请求方式
urlConn.setDoInput(true); //向连接中写入数据
urlConn.setDoOutput(true); //从连接中读取数据
urlConn.setUseCaches(false); //禁止缓存
urlConn.setInstanceFollowRedirects(true); //自动执行HTTP重定向
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded"); //设置内容类型
DataOutputStream out = new DataOutputStream(
urlConn.getOutputStream()); //获取输出流
//连接要提交的数据
String param = "username="
+ URLEncoder.encode(edit_Username.getText().toString(), "utf-8")
+ "&password="
+ URLEncoder.encode(edit_Password.getText().toString(), "utf-8");
out.writeBytes(param); //将要传递的数据写入数据输出流
out.flush(); //输出缓存
out.close(); //关闭数据输出流
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {//判断是否响应成功
InputStreamReader in = new InputStreamReader(
urlConn.getInputStream()); //获得读取的内容
BufferedReader buffer = new BufferedReader(in); //获取输入流对象
String inputLine = null;
//通过循环逐行读取输入流中的内容
while ((inputLine = buffer.readLine()) != null) {
result += inputLine;
}
in.close(); //关闭字符输入流
}
urlConn.disconnect(); //断开连接
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}