HttpURLConnection.getInputStream java.io.FileNotFoundException

2/10/2017来源:ASP.NET技巧人气:1327

判断getResponseCode,当返回不是HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED 时,不能用getInputStream(),而是应该用getErrorStream()

public String sendGet(String url, String param) {
		StringBuilder result = new StringBuilder();
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			URLConnection httpConnect = realUrl.openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection) httpConnect; 
			httpUrlConnection.connect();
		    	int responseCode = httpUrlConnection.getResponseCode();  
		    	InputStream inputStream = null;  
		    	if (responseCode == 200) {  
		    		inputStream = new BufferedInputStream(httpUrlConnection.getInputStream());  
		   	} else {  
		    		inputStream = new BufferedInputStream(httpUrlConnection.getErrorStream());  
		    	}  
			//in = new BufferedReader(new InputStreamReader(httpConnect.getInputStream(), "UTF-8"));
		    	in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			result.append(logUtil.getErrorStr(e));
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				result.append(logUtil.getErrorStr(e2));
			}
		}
		return result.toString();
	}