在 Android(Java/Kotlin)中处理HTTP错误400(错误请求)时,如果服务器返回的错误信息是“请求只有头部没有主体”,可以使用以下代码示例进行解决:
Java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String REQUEST_URL = "http://example.com/api/endpoint";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建一个线程来发送HTTP请求
new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建URL对象
URL url = new URL(REQUEST_URL);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取服务器响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 处理服务器响应
// ...
// 关闭连接和输入流
reader.close();
connection.disconnect();
} else {
// 处理HTTP错误
if(responseCode == HttpURLConnection.HTTP_BAD_REQUEST){
// 请求只有头部没有主体的错误
// ...
} else {
// 其他HTTP错误
// ...
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
Kotlin:
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
private val REQUEST_URL = "http://example.com/api/endpoint"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 创建一个线程来发送HTTP请求
Thread {
try {
// 创建URL对象
val url = URL(REQUEST_URL)
// 打开连接
val connection = url.openConnection() as HttpURLConnection
// 设置请求方法为GET
connection.requestMethod = "GET"
// 获取响应码
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取服务器响应
val reader = BufferedReader(InputStreamReader(connection.inputStream))
var line: String?
val response = StringBuilder()
while (reader.readLine().also { line = it } != null) {
response.append(line)
}
// 处理服务器响应
// ...
// 关闭连接和输入流
reader.close()
connection.disconnect()
} else {
// 处理HTTP错误
if (responseCode == HttpURLConnection.HTTP_BAD_REQUEST) {
// 请求只有头部没有主体的错误
// ...
} else {
// 其他HTTP错误
// ...
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}.start()
}
}
这段示例代码中发送了一个GET请求,如果服务器返回的响应码是HTTP_BAD_REQUEST(400),则会处理请求只有头部没有主体的错误。你可以在相应的位置添加你自己的代码来处理这个错误。