J2ME、诺基亚、HttpConnection

发布于 2024-11-25 00:41:15 字数 864 浏览 1 评论 0原文

该代码在索尼爱立信和摩托罗拉手机上运行良好,但在诺基亚手机上,它要么一开始就失败,根本不发出任何请求,要么返回空响应,具体取决于型号。

    HttpConnection hc = null;
    InputStream is = null;
    InputStreamReader isr = null;
    String result = "";

    try
    {
        hc = (HttpConnection) Connector.open(url);
        int rc = hc.getResponseCode();
        if (rc != HttpConnection.HTTP_OK)
        {
            throw new IOException(hc.getResponseMessage());
        }

        is = hc.openInputStream();
        isr = new InputStreamReader(is, "utf-8");
        int ch;
        while ((ch = is.read()) != -1)
        {
            result += (char) ch;
        }
    }
    finally
    {
        if (is != null)
        {
            is.close();
        }
        if (hc != null)
        {
            hc.close();
        }
    }

    return result;

尝试使用字节缓冲区、流等不同的代码,结果总是相同的。有什么问题吗?

This code works fine on SonyEricsson and Motorola cellphones, but on Nokia it either fails at the beginnig not making any request at all or returns empty response, depending on model.

    HttpConnection hc = null;
    InputStream is = null;
    InputStreamReader isr = null;
    String result = "";

    try
    {
        hc = (HttpConnection) Connector.open(url);
        int rc = hc.getResponseCode();
        if (rc != HttpConnection.HTTP_OK)
        {
            throw new IOException(hc.getResponseMessage());
        }

        is = hc.openInputStream();
        isr = new InputStreamReader(is, "utf-8");
        int ch;
        while ((ch = is.read()) != -1)
        {
            result += (char) ch;
        }
    }
    finally
    {
        if (is != null)
        {
            is.close();
        }
        if (hc != null)
        {
            hc.close();
        }
    }

    return result;

Tried different codes with byte buffers, streams, etc, result is always the same. What's the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尬尬 2024-12-02 00:41:16

尝试一下

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class Transport {

public static int BUFFER_LENGTH = 100;//1024;
public static boolean USE_FLUSH = false;

static {
    if (DeviceDetect.getDeivice() == DeviceDetect.SAMSUNG) {
        BUFFER_LENGTH = 1024;
        USE_FLUSH = true;
    }
}
public static String SESSION_COOKIE = null;


private static int rnd = 1;

private static final String request(String url, String method, Hashtable params) throws IOException {
    HttpConnection conn = null;
    DataOutputStream dos = null;
    InputStream in = null;

    try {

        String encodedParams = null;
        if (params != null && params.size() > 0) {
            encodedParams = getEncodedParams(params);
        }
        if (method == null) {
            if (encodedParams.length() < 2000) {
                method = "GET";
            } else {
                method = "POST";
            }
        }

        method = method != null && method.equalsIgnoreCase("POST") ? HttpConnection.POST : HttpConnection.GET;

        if (method.equalsIgnoreCase(HttpConnection.GET)) {
            if (encodedParams != null) {
                url += (url.indexOf("?") == -1 ? "?" : "&") + encodedParams;
                encodedParams = null;
            }
            url += (url.indexOf("?") == -1 ? "?" : "&") + "_rnd=" + rnd++;
        }

        conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
        if (conn == null) {
            throw new IOException("HttpConnection is null, please check Access Point configuration");
        }

        conn.setRequestMethod(method);
        conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        if (SESSION_COOKIE != null) {
            conn.setRequestProperty("Cookie", SESSION_COOKIE);
        }

        byte[] buff = new byte[BUFFER_LENGTH];
        if (encodedParams != null) {
            byte[] bytes = encodedParams.getBytes("UTF-8");
            String lengthStr = bytes.length + "";
            conn.setRequestProperty("Content-Length", lengthStr);

            dos = conn.openDataOutputStream();
            if (dos == null) {
                throw new IOException("OutputStream is null, please check Access Point configuration");
            }

            for (int i = 0, l = bytes.length; i < l; i += Transport.BUFFER_LENGTH) {
                if (Transport.BUFFER_LENGTH == 1) {
                    dos.writeByte(bytes[i]);
                } else {
                    int count = Math.min(Transport.BUFFER_LENGTH, l - i);
                    System.arraycopy(bytes, i, buff, 0, count);
                    dos.write(buff, 0, count);
                }
                if (Transport.USE_FLUSH) {
                    dos.flush();
                }
            }

            dos.flush();
            try {
                dos.close();
            } catch (IOException ex) {
            }
        }

        String setCookie = conn.getHeaderField("Set-Cookie");
        if (setCookie != null) {
            int ind1 = setCookie.indexOf("JSESSIONID=");
            if (ind1 > -1) {
                int ind2 = setCookie.indexOf(";", ind1);
                SESSION_COOKIE = ind2 == -1 ? setCookie.substring(ind1) : setCookie.substring(ind1, ind2 + 1);
            }
        }

        in = conn.openInputStream();
        if (in == null) {
            throw new IOException("InputStream is null, please check Access Point configuration");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int n = in.read(buff);
        while (n > -1) {
            baos.write(buff, 0, n);
            n = in.read(buff);
        }
        baos.flush();
        baos.close();
        String response = new String(baos.toByteArray(), "UTF-8");
        try {
            in.close();
        } catch (Exception ex) {
        }
        try {
            conn.close();
        } catch (Exception ex) {
        }

        return response;
    } finally {
        try {
            dos.close();
        } catch (Exception ex) {
        }
        try {
            in.close();
        } catch (Exception ex) {
        }
        try {
            conn.close();
        } catch (Exception ex) {
        }
    }

}

public static String getEncodedParams(Hashtable params) throws IOException {
    String str = "";
    Enumeration keys = params.keys();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        Object value = params.get(name);
        if (value == null || name == null) {
            continue;
        }            
        str += "&" + URLEncoder.encode(name.toString(), "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8");
    }
    if (str.length() > 1) {
        str = str.substring(1);
    }
    return str;
}
}

try it

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class Transport {

public static int BUFFER_LENGTH = 100;//1024;
public static boolean USE_FLUSH = false;

static {
    if (DeviceDetect.getDeivice() == DeviceDetect.SAMSUNG) {
        BUFFER_LENGTH = 1024;
        USE_FLUSH = true;
    }
}
public static String SESSION_COOKIE = null;


private static int rnd = 1;

private static final String request(String url, String method, Hashtable params) throws IOException {
    HttpConnection conn = null;
    DataOutputStream dos = null;
    InputStream in = null;

    try {

        String encodedParams = null;
        if (params != null && params.size() > 0) {
            encodedParams = getEncodedParams(params);
        }
        if (method == null) {
            if (encodedParams.length() < 2000) {
                method = "GET";
            } else {
                method = "POST";
            }
        }

        method = method != null && method.equalsIgnoreCase("POST") ? HttpConnection.POST : HttpConnection.GET;

        if (method.equalsIgnoreCase(HttpConnection.GET)) {
            if (encodedParams != null) {
                url += (url.indexOf("?") == -1 ? "?" : "&") + encodedParams;
                encodedParams = null;
            }
            url += (url.indexOf("?") == -1 ? "?" : "&") + "_rnd=" + rnd++;
        }

        conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
        if (conn == null) {
            throw new IOException("HttpConnection is null, please check Access Point configuration");
        }

        conn.setRequestMethod(method);
        conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        if (SESSION_COOKIE != null) {
            conn.setRequestProperty("Cookie", SESSION_COOKIE);
        }

        byte[] buff = new byte[BUFFER_LENGTH];
        if (encodedParams != null) {
            byte[] bytes = encodedParams.getBytes("UTF-8");
            String lengthStr = bytes.length + "";
            conn.setRequestProperty("Content-Length", lengthStr);

            dos = conn.openDataOutputStream();
            if (dos == null) {
                throw new IOException("OutputStream is null, please check Access Point configuration");
            }

            for (int i = 0, l = bytes.length; i < l; i += Transport.BUFFER_LENGTH) {
                if (Transport.BUFFER_LENGTH == 1) {
                    dos.writeByte(bytes[i]);
                } else {
                    int count = Math.min(Transport.BUFFER_LENGTH, l - i);
                    System.arraycopy(bytes, i, buff, 0, count);
                    dos.write(buff, 0, count);
                }
                if (Transport.USE_FLUSH) {
                    dos.flush();
                }
            }

            dos.flush();
            try {
                dos.close();
            } catch (IOException ex) {
            }
        }

        String setCookie = conn.getHeaderField("Set-Cookie");
        if (setCookie != null) {
            int ind1 = setCookie.indexOf("JSESSIONID=");
            if (ind1 > -1) {
                int ind2 = setCookie.indexOf(";", ind1);
                SESSION_COOKIE = ind2 == -1 ? setCookie.substring(ind1) : setCookie.substring(ind1, ind2 + 1);
            }
        }

        in = conn.openInputStream();
        if (in == null) {
            throw new IOException("InputStream is null, please check Access Point configuration");
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int n = in.read(buff);
        while (n > -1) {
            baos.write(buff, 0, n);
            n = in.read(buff);
        }
        baos.flush();
        baos.close();
        String response = new String(baos.toByteArray(), "UTF-8");
        try {
            in.close();
        } catch (Exception ex) {
        }
        try {
            conn.close();
        } catch (Exception ex) {
        }

        return response;
    } finally {
        try {
            dos.close();
        } catch (Exception ex) {
        }
        try {
            in.close();
        } catch (Exception ex) {
        }
        try {
            conn.close();
        } catch (Exception ex) {
        }
    }

}

public static String getEncodedParams(Hashtable params) throws IOException {
    String str = "";
    Enumeration keys = params.keys();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        Object value = params.get(name);
        if (value == null || name == null) {
            continue;
        }            
        str += "&" + URLEncoder.encode(name.toString(), "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8");
    }
    if (str.length() > 1) {
        str = str.substring(1);
    }
    return str;
}
}
孤城病女 2024-12-02 00:41:16

我不确定这是否适合您,但我遇到了类似的问题,并发现指定端口号可以使其工作(在某些较旧的诺基亚型号上)。即转换:

 http://www.mysite.com/my_page.html

为:

http://mysite.com:80/my_page.html

I am not sure if this will work for you but I had a similar problem and found that specifying a port number made it work (on some older Nokia models). i.e convert:

 http://www.mysite.com/my_page.html

to:

http://mysite.com:80/my_page.html
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文