我是android新手,即将编写与REST-API通信的第一个应用程序。我设法执行了GET请求,但是POST请求遇到了问题。一切都可以在Postman中运行-在Android上,每次尝试执行POST请求时,我的AsyncTask都会引发FileNotFound异常。
按照API的文档,我首先需要通过HTTP GET请求(https://vereinsflieger.de/interface/rest/auth/accesstoken)获得一个“访问令牌”,我已经成功地做到了这一点。现在,使用访问令牌,我要通过https://vereinsflieger.de/interface/rest/auth/signin上的POST请求登录。因为我不知道是什么原因,即使文件存在,我的AsyncTask也会引发FileNotFound异常(在Postman中可以正常工作)。我正在使用的代码或API本身有问题吗?
提前谢谢!
这是我的尝试:
public class HttpPostRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "POST";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
public String result;
public LoginActivity LoginActivity;
public HttpPostRequest(LoginActivity a) { this.callingActivity = a; }
@Override
protected String doInBackground(String... params) {
String stringURL = params[0];
String logindata = params[1];
String inputLine;
try {
//create URL object
URL myUrl = new URL(stringURL);
//create connection
HttpsURLConnection connection = (HttpsURLConnection) myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
**connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(logindata);
wr.flush();**
Log.d("RESPONSE", "" + connection.getResponseCode());
//Create a new InputStreamReader
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
**StringBuilder stringBuilder = new StringBuilder();** //Here is where the exception is thrown
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
} catch(IOException e){
e.printStackTrace();
result = null;
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
LoginActivity.onPostFinish(result);
}
}
我希望返回一个包含JSON数据的字符串,相反,我得到了以下异常:
W/System.err: java.io.FileNotFoundException: https://vereinsflieger.de/interface/rest/auth/signin
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250)
W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)