Android HttpUrlConnection FileNotFoundException。连接到http并传递参数
Android HttpUrlConnection FileNotFoundException. Connect to http and pass params
public class GeoRegistration extends AsyncTask<Void, Void, AuthorizationResponseContainer> {
private Activity activity;
private static final String USERNAME = "username=";
private static final String EMAIL = "&email=";
private static final String PASSWORD = "&password=";
private static final String PASSWORD_REPEAT = "&password_repeat=";
private String route;
private String paramsSequence;
public GeoRegistration() {
}
public GeoRegistration(Activity activity, String username, String email, String password, String passwordConfirm) {
this.activity = activity;
this.route = activity.getResources().getString(R.string.domain) + activity.getResources().getString(R.string.registration_second_step_route);
this.paramsSequence = USERNAME + username +
EMAIL + email +
PASSWORD + password +
PASSWORD_REPEAT + passwordConfirm;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected AuthorizationResponseContainer doInBackground(Void... params) {
String message = null;
int code = 0;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(route);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("POST"); //Sometimes (it's very strange, I catch ProtocolExeption: Connection already established)
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
/*PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
out.print(this.paramsSequence);
out.close();*/
OutputStream os = httpURLConnection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(paramsSequence);
osw.flush();
osw.close();
httpURLConnection.connect();
int status = httpURLConnection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); //FileNotFounException
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
JSONObject jsonObject = new JSONObject(builder.toString());
message = jsonObject.getString(ResponseKeys.MESSAGE);
code = jsonObject.getInt(ResponseKeys.CODE);
switch (status) {
case 200:
if (code == 0) {
}
return null;
case 400:
return new AuthorizationResponseContainer(ResponseKeys.CODE_400, code, message, null);
case 500:
return new AuthorizationResponseContainer(ResponseKeys.CODE_500, code, message, null);
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
try {
httpURLConnection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
路线:http://geo.binno.com.ua/api/m1/registration/
为什么我无法从 HttpUrlConnection 获取输入流?我捕获了 FileNotFoundException。但是当我在浏览器中的 REST API 客户端执行相同操作时,我可以连接到主机并接收 json 答案。我做错了什么?
我被作为字符串传递了 http 参数,需要作为 JSON - 这是第一个。
当服务器回答 4xx 代码时 - 需要获取 ErrorStream,而不是 InputStream
示例:
int respCode = conn.getResponseCode();
Bufferreader reader;
switch(respCode){
case 200:
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); //to avoid FNFExeption
break;
case 400:
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream())); //to avoid FNFExeption
break;
}
添加这些代码行..
httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
httpURLConnection.setRequestProperty("Accept", "*/*");
和
try {
is = connection.getInputStream();
} catch(FileNotFoundException exception){
log.error(exception.getMessage(), exception);
is = connection.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
希望这能解决您的问题。谢谢...
public class GeoRegistration extends AsyncTask<Void, Void, AuthorizationResponseContainer> {
private Activity activity;
private static final String USERNAME = "username=";
private static final String EMAIL = "&email=";
private static final String PASSWORD = "&password=";
private static final String PASSWORD_REPEAT = "&password_repeat=";
private String route;
private String paramsSequence;
public GeoRegistration() {
}
public GeoRegistration(Activity activity, String username, String email, String password, String passwordConfirm) {
this.activity = activity;
this.route = activity.getResources().getString(R.string.domain) + activity.getResources().getString(R.string.registration_second_step_route);
this.paramsSequence = USERNAME + username +
EMAIL + email +
PASSWORD + password +
PASSWORD_REPEAT + passwordConfirm;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected AuthorizationResponseContainer doInBackground(Void... params) {
String message = null;
int code = 0;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(route);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("POST"); //Sometimes (it's very strange, I catch ProtocolExeption: Connection already established)
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
/*PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
out.print(this.paramsSequence);
out.close();*/
OutputStream os = httpURLConnection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(paramsSequence);
osw.flush();
osw.close();
httpURLConnection.connect();
int status = httpURLConnection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); //FileNotFounException
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
JSONObject jsonObject = new JSONObject(builder.toString());
message = jsonObject.getString(ResponseKeys.MESSAGE);
code = jsonObject.getInt(ResponseKeys.CODE);
switch (status) {
case 200:
if (code == 0) {
}
return null;
case 400:
return new AuthorizationResponseContainer(ResponseKeys.CODE_400, code, message, null);
case 500:
return new AuthorizationResponseContainer(ResponseKeys.CODE_500, code, message, null);
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
try {
httpURLConnection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
路线:http://geo.binno.com.ua/api/m1/registration/
为什么我无法从 HttpUrlConnection 获取输入流?我捕获了 FileNotFoundException。但是当我在浏览器中的 REST API 客户端执行相同操作时,我可以连接到主机并接收 json 答案。我做错了什么?
我被作为字符串传递了 http 参数,需要作为 JSON - 这是第一个。 当服务器回答 4xx 代码时 - 需要获取 ErrorStream,而不是 InputStream 示例:
int respCode = conn.getResponseCode();
Bufferreader reader;
switch(respCode){
case 200:
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); //to avoid FNFExeption
break;
case 400:
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream())); //to avoid FNFExeption
break;
}
添加这些代码行..
httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
httpURLConnection.setRequestProperty("Accept", "*/*");
和
try {
is = connection.getInputStream();
} catch(FileNotFoundException exception){
log.error(exception.getMessage(), exception);
is = connection.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
希望这能解决您的问题。谢谢...