本文專注於 HttpURLConnection 的數據傳輸核心邏輯,不包含 UI 操作及中文亂碼處理。實際開發中網絡請求需在子線程執行。
package com.example.httpurlconnectiontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.content.Context;
import android.widget.Toast;
public class HttpThread extends Thread {
private String url;
private String name;
private String age;
private Context context;
public HttpThread(Context context, String url, String name, String age) {
this.context = context;
this.url = url;
this.name = name;
this.age = age;
}
private void doGet() {
url = url + "?username=" + name + "&password=" + age;
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while ((str = reader.readLine()) != null) {
sb.append(str);
}
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void doPost() {
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
OutputStream out = conn.getOutputStream();
String content = "username=" + name + "&password=" + age;
out.write(content.getBytes());
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while ((str = reader.readLine()) != null) {
sb.append(str);
}
System.out.println(sb);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
// doGet();
doPost();
}
}
String url = "https://115.158.57.173:8080/KuaiDi3/AddUser_servlet";
new HttpThread(MainActivity.this, url, "123", "123").start();
關鍵點總結:
conn.getInputStream() 讀取響應。conn.getOutputStream() 寫入參數數據,同樣用 getInputStream() 讀取響應。setReadTimeout(5000))。