下面是我的代码段。 403错误即将到来。任何人都可以提出解决方案以克服此403错误。这是发布JSON请求。
@Override
protected String doInBackground(Void... voids) {
try {
trustAllHosts();
URL url = new URL(postUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userCredentials = username+":"+password;
String basicAuth = "Basic " + new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("X-CSRF-TOKEN",token);
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
PostRootObject postRootObject = new PostRootObject();
Gson gson = new GsonBuilder().create();
String json = gson.toJson(postRootObject);
JSONObject jsonObject = new JSONObject(json);
Log.e("Json object",""+jsonObject);
DataOutputStream os = new
DataOutputStream(conn.getOutputStream());
// os.writeBytes(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
os.writeBytes(jsonObject.toString());
os.flush();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
os.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
答案 0 :(得分:0)
也许清单文件中缺少此行:
<uses-permission android:name="android.permission.INTERNET" />