简体   繁体   中英

J2ME, Nokia, HttpConnection

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?

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

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). ie convert:

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

to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM