0

我将 BufferedInputStream 用于 HTTP POST/GET

但是我在下面遇到了一些错误

  1. java.io.FileNotFoundException:http://XX.XX.XX.XX/WebWS/data.aspx
  2. 传输端点未连接

为什么会出现此错误。我的代码在下面

URL url = new URL(glob.postUrl);

    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

    try {

        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setRequestMethod("GET");
        httpConn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        httpConn.setRequestProperty("Content-Language", "TR");      
        httpConn.setConnectTimeout(12000);


        Iterator<String> reqProps = hMap.keySet().iterator();
        while (reqProps.hasNext()) {
            String key = reqProps.next();
            String value = hMap.get(key);
            httpConn.addRequestProperty(key, value);
        }

        InputStream in = new BufferedInputStream(httpConn.getInputStream());

        StringBuilder builder = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } finally {
            in.close();
        }
        httpConn.disconnect();

谢谢。

4

2 回答 2

2

你有什么理由不使用HttpClient吗?

您可以将代码替换为以下内容:

HttpContext httpContext = new BasicHttpContext();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String page = EntityUtils.toString(entity);

您可以使用 ClientConnectionManager 和 HttpParams 设置 HttpClient 以在初始化时为客户端设置安全性和各种 http 参数(如果您搜索类名,则有大量示例)。

于 2011-07-01T14:31:27.770 回答
0

HttpURLConnectionImpl.getInputStream()FileNotFoundException如果 HTTP 响应状态代码为 400 或更高,即对于服务器端的任何错误情况,已知会抛出 a 。您应该检查状态代码到底是什么,以获得合适的调试信息。

但是,我赞同 Mark Fisher 关于使用 HttpClient 的建议,AFAIK 是在 Android 上使用 HTTP 的首选方式。

于 2011-07-01T15:00:25.927 回答