我尝试将 token 发送到我的应用程序中 header 中的服务器端。但是当我尝试发送 token 时出现此错误
org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
我的服务器端是laravel。
即使我尝试使用 utf-8
但它不起作用
con.addRequestProperty("Authorization", "Bearer " + token+"; charset=utf-8" );
这是我连接到服务器时的代码
@Override
protected Object doInBackground(Object[] objects) {
try {
URL url = new URL(objects[URL_ADDRESS].toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(objects[CONNECTION_METHOD].toString());
if (token != null) {
con.addRequestProperty("Authorization", "Bearer " + token+"; charset=utf-8" );
}
if (objects[CONNECTION_METHOD].toString().equals("POST")) {
con.addRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
out.write(objects[OUTPUT_OBJECT].toString().getBytes("UTF-8"));
}
String str;
if (con.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
str = getRespons(con.getInputStream()) /*+ jsRespons*/;
} else {
str = getRespons(con.getErrorStream()) /*+ jsRespons*/;
}
///
Map<String, List<String>> headerFields = con.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
List<String> headerFieldValue = headerFields.get(headerFieldKey);
StringBuilder sb = new StringBuilder();
for (String value : headerFieldValue) {
sb.append(value);
sb.append("");
}
System.out.println(headerFieldKey + "=" + sb.toString() );
}
///
JSONObject jsResponse = new JSONObject(str);
jsResponse.put("resMsg", con.getResponseMessage());
jsResponse.put("response", con.getResponseCode());
return jsResponse.toString();
} catch (Exception e) {
return e.toString();
}
}
谢谢。
最佳答案
根据 Laravel documentation 将 Accept: application/json
header 添加到您的请求中.
con.addRequestProperty("Accept", "application/json");
关于java - 如何修复 Android 中的 "Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315814/