我正在执行Android应用程序开发的第一步,我使用AndroidStudio,但是当我尝试使用POST方法发送http resquest并获取结果(结果是一个简单的字符串)时,我捕获到异常消息null。
感谢您的帮助。
我试图这样做只是看我是否获得响应代码200,但仍然为null, 尝试连接中发生异常,并且e.getMessage()返回null
try { URL uri = new URL("http://google.com"); con = (HttpURLConnection) uri.openConnection(); rep = Integer.toString(con.getResponseCode()); }catch (Exception e){ //rep = e.getMessage(); rep = " fail to connect"; }
完整功能
public String sendPostRequest(String url, String data) {
HttpURLConnection con=null;
String rep="";
try {
URL uri = new URL(url);
con = (HttpURLConnection) uri.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/x-www-
form-urlencoded");
con.setRequestProperty("Content-Length",
String.valueOf(postData.length));
con.getOutputStream().write(postData);
con.getOutputStream().flush();
con.getOutputStream().close();
StringBuilder content;
Reader reader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
for (int c; (c = reader.read()) >= 0; )
sb.append((char) c);
rep = sb.toString();
}
catch (Exception e){
rep = e.getMessage();
}
finally {
con.disconnect();
}
return rep;