HttpUrlConnection抛出FileNotFound异常,其中json对象在DataOutputStream中传递。如何解决这个问题? 为什么抛出FileNotFound异常?
public final String apiCall(String pUrl,JSONObject jsonObject) {
try {
URL url = new URL(pUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
try{
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line = bufferedReader.readLine())!= null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
return "ERROR";
} finally{
bufferedReader.close();
httpURLConnection.disconnect();
}
}catch (Exception e) {
return "ERROR";
}
}
答案 0 :(得分:0)
过去我遇到了同样的问题。我遇到了错误的参数问题。现在花了一些时间后我才能解决我的问题。为别人提供答案。将错误的电子邮件和密码传递给服务是正确的,服务器也在使用这些参数,因为有错误(因为电子邮件和密码),这就是它返回500代码的原因。所以,我检查状态代码是否为200然后我使用了getInputStream()方法,否则我调用了getErrorStream()方法。通过这种方式,我得到了具有错误属性的流(此属性包含错误详细信息)。以下是我使用的代码
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
背后的主要思想是首先检查响应代码。如果这是代码中提到的HTTP_OK,则表示没有问题,如果没有,则转到错误流以检查从服务器收到的错误是什么。希望有所帮助。
答案 1 :(得分:0)
您的网址可能存在问题,您可以编码然后重试。
您可以尝试:
protected static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection();