【问题标题】:Android BufferedInputStream HTTP POST/GETAndroid BufferedInputStream HTTP POST/GET
【发布时间】:2011-07-01 13:54:55
【问题描述】:

我将 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();

谢谢。

【问题讨论】:

    标签: android http post get bufferedinputstream


    【解决方案1】:

    你有什么理由不使用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 参数(如果您搜索类名,周围有很多示例)。

    【讨论】:

    • 使用完实体后不要忘记致电entity.consumeContent()
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多