Модераторы: javastic, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> error 10053 during TCP read, попадалось? 
:(
    Опции темы
DEMOVERSION
Дата 14.3.2006, 21:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 105
Регистрация: 18.10.2005

Репутация: нет
Всего: 1



Знакомо кому-то?

Вот такой код к этому приводит в WTK22(в Nokia Prototype 4.0 S60 все ОК).
Падает все на connection.getResponseCode() , возвращает -1 и сабж.

Спасибо.

Код

    public synchronized String executeRequestQuery(String query,int nt) {
                System.out.println("Executing query at " + new Date() + " query=" + query + ";sessionId="+sessionId+";url="+gameURL);
        String result = "";
                HttpConnection connection = null;
                InputStream is = null;
                OutputStream os = null;
        long len = 0;
        try {
                connection = (HttpConnection)Connector.open(gameURL);
                connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("cookie","JSESSIONID=" + sessionId + "; AnyJavaPresent=1.4.2_05");
                connection.setRequestProperty("Cache-Control","no-cache");
                connection.setRequestProperty("Pragma","no-cache");
                connection.setRequestProperty("User-Agent","Mozilla/4.0 (Windows XP 5.1) Java/1.4.2_05");
                connection.setRequestProperty("Accept","text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
                connection.setRequestProperty("Connection","keep-alive");
                
                connection.setRequestMethod("POST");

                os = connection.openOutputStream();
                // wait for 0.02 second
//                try {
//                    Thread.sleep(20);
//                } catch (Exception ieo) {
//                    System.out.println("Sleep error");
//                }
                // open output stream
                os.write(query.getBytes());
                os.flush();
                
                            // get response code
                            if(connection.getResponseCode() == HttpConnection.HTTP_OK) {
                                is = connection.openInputStream();
                                len = connection.getLength();
                                System.out.println("Response Lenght :" + len);
                            if (len!=-1) {
                                byte servletData[] = new byte[(int)len];
                                is.read(servletData);
                                result = new String(servletData);
                                }
                             }
                               else { // not HttpConnection.OK
                                Alert alert = new Alert("Error!");
                                alert.setString(connection.getResponseMessage());
                                alert.setTimeout(Alert.FOREVER);
                                MobileWindowManager.getInstance().setScreenWindow(alert,false,"ALERT");
                                MobileWindowManager.getInstance().setScreenWindow(GameWindow.NAME);
                               }
                } catch (IOException e) {
                        System.out.println("Error while connecting: "  + e.getMessage());
                        e.printStackTrace();
                }
                finally {
                    // close connections
                    try {
                    if (is!=null)
                        is.close();
                    is = null;
                    if (os != null)
                        os.close();
                    os = null;
                    if (connection!=null)
                        connection.close();
                    connection = null;
                    } catch (IOException ioe) {
                        System.out.println("Error while closing is,os,connection");
                    }
                }
        // try again?!?
                System.out.println("numberOfTries:" + nt );
                if (result.indexOf("SESSIONERROR")!=-1&&nt>0) {
                    result = executeRequestQuery(query,nt-1);
                } 
        return result;
        }

PM MAIL   Вверх
javastic
Дата 15.3.2006, 14:33 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Комодератор
Сообщений: 1214
Регистрация: 18.3.2005
Где: St.Petersburg

Репутация: 19
Всего: 27



У меня такое было когда я передавал данные объемом больше 2Кб, тогда телефон передаёт chunk блоками и возвращает код ошибки 100 Continue. Включе Network monitor и посмотри http заголовки. Можешь запостить их сюда. Так же в настроках secuirity не забудь добаввить класс HttpConnection.

При chunk блоках нужно передавать данные не более 2Кб, а flush делать в самом конце.


--------------------
01101010 01100001 01110110 01100001 01110011 01110100 01101001 01100011
scjp, mcp 
PM MAIL WWW ICQ   Вверх
redrick
Дата 15.3.2006, 15:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 547
Регистрация: 7.1.2004
Где: Москва

Репутация: 1
Всего: 5



кстати, flush() это такая заподлистая штука
http://www.devx.com/getHelpOn/10MinuteSolu...646/1763/page/3

вообще она ведь не обязательна - connection.getResponseCode() сделает flush() само:
MIDP 2.0 javadoc
Код

 Example using POST with HttpConnection

Post a request with some headers and content to the server and process the headers and content.

Connector.open is used to open url and a HttpConnection is returned. The request method is set to POST and request headers set. A simple command is written and flushed. The HTTP headers are read and processed. If the length is available, it is used to read the data in bulk. From the HttpConnection the InputStream is opened. It is used to read every character until end of file (-1). If an exception is thrown the connection and stream is closed.

    void postViaHttpConnection(String url) throws IOException {
        HttpConnection c = null;
        InputStream is = null;
        OutputStream os = null;
        int rc;

        try {
            c = (HttpConnection)Connector.open(url);

            // Set the request method and headers
            c.setRequestMethod(HttpConnection.POST);
            c.setRequestProperty("If-Modified-Since",
                "29 Oct 1999 19:43:31 GMT");
            c.setRequestProperty("User-Agent",
                "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            c.setRequestProperty("Content-Language", "en-US");

            // Getting the output stream may flush the headers
            os = c.openOutputStream();
            os.write("LIST games\n".getBytes());
            [B]os.flush();           // Optional, getResponseCode will flush[/B]

            // Getting the response code will open the connection,
            // send the request, and read the HTTP response headers.
            // The headers are stored until requested.
            rc = c.getResponseCode();
            if (rc != HttpConnection.HTTP_OK) {
                throw new IOException("HTTP response code: " + rc);
            }

            is = c.openInputStream();

            // Get the ContentType
            String type = c.getType();
            processType(type);

            // Get the length and process the data
            int len = (int)c.getLength();
            if (len > 0) {
                 int actual = 0;
                 int bytesread = 0 ;
                 byte[] data = new byte[len];
                 while ((bytesread != len) && (actual != -1)) {
                    actual = is.read(data, bytesread, len - bytesread);
                    bytesread += actual;
                 }
                process(data);
            } else {
                int ch;
                while ((ch = is.read()) != -1) {
                    process((byte)ch);
                }
            }
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Not an HTTP URL");
        } finally {
            if (is != null)
                is.close();
            if (os != null)
                os.close();
            if (c != null)
                c.close();
        }
    }
 



я в свое время долго втыкал почему это мой проект перестал работать на Sony Ericson вообще


--------------------
Имею Мнение Хрен Оспоришь   
PM MAIL ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса

  • Прежде чем задать вопрос прочтите это!
  • Литература по Java находится здесь.
  • Литературу по Java обсуждаем здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит" (возле кнопок кодов) если у Вас нет русских шрифтов.
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда

  • FAQ раздела лежит здесь!
 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java ME (J2ME) | Следующая тема »


 




[ Время генерации скрипта: 0.0781 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.