HttpURLConnection GETは、具体的な情報がない場合に判定に成功する
2889 ワード
今日HttpURLConnectionでgetリクエストを書いたとき、いつも間違っていることに気づき、後で問題を発見し、後で忘れないようにメモしました.
返信中にメッセージがない場合、connection.getResponseCode()が200で成功したかどうかを判断する
POSTメソッドの使用:
/**
*
*
* @param response
* @param json
*/
public static String transferForGet(String data,String serverUrl) {
//
URL url;
try {
url = new URL(serverUrl);
} catch (MalformedURLException e1) {
Util.err(e1);
return "fail";
}
//
HttpURLConnection connection = null;
String strResponse = "";
BufferedReader reader = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
connection.getInputStream();
strResponse = connection.getResponseCode()+":"+connection.getResponseMessage();
} catch (ProtocolException e) {
Util.err(e);
} catch (IOException e) {
Util.err(e);
} finally{
try{
if(reader != null){
reader.close();
}
}catch(Exception e){}
try{
connection.disconnect();
}catch(Exception e){
Util.err(e);
}
}
if(strResponse == null || strResponse.equals(""))
return "fail";
return strResponse;
}
返信中にメッセージがない場合、connection.getResponseCode()が200で成功したかどうかを判断する
POSTメソッドの使用:
/**
*
*
* @param response
* @param json
*/
public static String transfer(String data,String serverUrl) {
//
URL url;
try {
url = new URL(serverUrl);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
Util.err(e1);
return "fail";
}
//
HttpURLConnection connection = null;
String strResponse = "";
BufferedReader reader = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(50 * 1000);// 10
connection.setReadTimeout(50 * 1000);// 10
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"text/html; charset=utf-8");
connection.setRequestProperty("Connection", "close");
//
OutputStreamWriter output = new OutputStreamWriter(connection
.getOutputStream(),"UTF-8");
output.write(data);
output.flush();
output.close();
//
String strLine = "";
InputStream in = connection.getInputStream();
reader = new BufferedReader(
new InputStreamReader(in,"UTF-8"));
while ((strLine = reader.readLine()) != null) {
strResponse += strLine ;
}
} catch (ProtocolException e) {
Util.err(e);
} catch (IOException e) {
Util.err(e);
} finally{
try{
if(reader != null){
reader.close();
}
}catch(Exception e){}
try{
connection.disconnect();
}catch(Exception e){
Util.err(e);
}
}
if(strResponse == null || strResponse.equals(""))
return "fail";
return strResponse;
}