可以先确认发送请求时的数据格式和请求头是否正确,如果数据格式不对或者请求头缺失可能导致API返回400错误。
示例代码如下:
public static String httpRequest(String url, String method, String params) {
URL obj;
HttpURLConnection con;
BufferedReader in;
StringBuffer response = new StringBuffer();
try {
obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod(method);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
if (params != null) {
OutputStream os = con.getOutputStream();
os.write(params.getBytes("UTF-8"));
os.flush();
os.close();
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
response.append("{\"status\":\"error\",\"message\":\"" +
"HTTP Error Code: " + responseCode + "\"}");
}
} catch (IOException e) {
e.printStackTrace();
response.delete(0, response.length());
response.append("{\"status\":\"error\",\"message\":\"" +
"IOException: " + e.getMessage() + "\"}");
}
return response.toString();
}
在使用此方法发送请求时,需要确保传入的数据格式是符合API要求的,例如JSON格式、XML格式等。同时,可以根据API的要求修改请求头中的属性,例如Accept、Authorization等。