开发者

Android BufferedInputStream HTTP POST/GET

开发者 https://www.devze.com 2023-03-16 22:26 出处:网络
I Use BufferedInputStream For HTTP POST/GET But I Get Some Error the Below java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx

I Use BufferedInputStream For HTTP POST/GET

But I Get Some Error the Below

  1. java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx
  2. Transport endpoint is not connected

Why Get This Error. My Code is Below

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.setCon开发者_Go百科nectTimeout(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();

Thanks.


Is there any reason you're not using HttpClient?

You can replace your code with something like:

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);

You can setup the HttpClient with ClientConnectionManager and HttpParams for security and various http parameters for the client at initialisation (plenty of examples around if you search on class names).


HttpURLConnectionImpl.getInputStream() is known to throw a FileNotFoundException if the HTTP response status code is 400 or higher, i.e. for any error condition on the server side. You should check what the status code really is in order to obtain suitable debug information.

However, I second Mark Fisher's suggestion about using HttpClient, which AFAIK is the preferred way of working with HTTP on Android.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号