我正在创建一个使用connectify连接到我的电脑的Android应用程序并执行http获取请求并且工作正常但是当我尝试使用我的服务器在互联网上使用我的本地休息api的副本时没有#t工作帮助我,请提前感谢这是我的代码
public static String makeRequest(RequestPackage p) throws Exception {
BufferedReader reader = null;
int status =0;
String uri = p.getUri();
if(p.getMethod().equals("GET")){
uri += "?" + p.getEncondedParams();
}
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod(p.getMethod());
if (p.getMethod().equals("POST")){
con.setDoOutput(true);
con.setChunkedStreamingMode(0);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(p.getEncondedParams());
writer.flush();
status = con.getResponseCode();
}
StringBuilder sb = new StringBuilder();
con.setConnectTimeout(30000);
con.setReadTimeout(30000);
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null){
sb.append(line+"\n");
}
con.disconnect();
return sb.toString();
}
答案 0 :(得分:0)
我认为您可以查看回复代码。如果它不是200(OK),则getInputStream可能返回null,然后使用getErrorStream。希望这有帮助,因为我昨天遇到了同样的问题。
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}