使用HttpURLConnection发送raw POST请求到授权系统报错如何解决?
错误原因
- 请求头配置错误:代码中设置
Content-Type时多写了头名前缀,实际传入值为Content-Type: application/x-www-form-urlencoded,不符合HTTP头规范,服务端无法正确识别请求体格式。 - 请求体格式不匹配:目标接口要求提交
application/x-www-form-urlencoded格式的表单参数(结构为key1=value1&key2=value2),但代码中将Gson构造的JSON对象直接转为字符串发送,服务端按表单规则解析时无法读取到type参数,因此返回Invalid type错误。
修复方案
首先修正Content-Type请求头的配置,然后将JSON构造逻辑替换为表单参数拼接逻辑,同时对参数值做URL编码避免特殊字符导致解析失败,修改后代码如下:
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.StringJoiner; public int LoginWithUserPass(String user, String pass) throws Exception { URL url = new URL("https://api.auth.gg/v1/"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "LoginSystem"); // 修正Content-Type头的取值 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 构造表单参数 Map<String, String> params = new HashMap<>(); params.put("type", "login"); params.put("hwid", getHWID()); params.put("password", pass); params.put("username", user); params.put("secret", "test"); params.put("apikey", apikey); params.put("aid", "test"); // 拼接为urlencoded格式,参数做URL编码 StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : params.entrySet()) { String key = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name()); String value = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()); sj.add(key + "=" + value); } byte[] postBody = sj.toString().getBytes(StandardCharsets.UTF_8); // 设置请求体长度 con.setRequestProperty("Content-Length", String.valueOf(postBody.length)); // 写入请求体 try (OutputStream os = con.getOutputStream()) { os.write(postBody); } if (con.getResponseCode() == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(sb.toString()); if (!element.getAsJsonObject().get("result").getAsString().equalsIgnoreCase("failed")) { System.out.println("Successfully Logged in!"); } else { System.out.println(element.getAsJsonObject()); return -1; } } return con.getResponseCode(); }
内容的提问来源于stack exchange,提问作者JombiBestwww
相关产品推荐
相关产品推荐

