黑莓OS 5 - 7 - 试图让JSON响应,并得到错误code 500 [英] BlackBerry OS 5 - 7 - Trying to get JSON response and get error code 500

查看:210
本文介绍了黑莓OS 5 - 7 - 试图让JSON响应,并得到错误code 500的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图从我公司的JSON web服务的JSON响应。这里是code:

 公共最后静态字符串GOINOUT_HOST_NAME =htt​​p://ec2-54-254-123-244.ap-southeast-1.compute.amazonaws.com;
公共最后静态字符串GOINOUT_API_VERSION =/ API / V1;公共最后静态字符串GOINOUT_FACEBOOK_AUTHENTICATE = GOINOUT_HOST_NAME + GOINOUT_API_VERSION +/ facebook_authenticate;公共静态的JSONObject loginGoinoutWithFacebook(字符串的accessToken){
    JSONObject的goinoutUserJsonObject = NULL;
    尝试{
        Hashtable的PARAMS =新的Hashtable();
        params.put(的access_token的accessToken);
        字符串paramsString = StringUtil.toURLParameters(PARAMS);        Hashtable的性能=新的Hashtable();
        串响应= HttpUtils.sendGoinoutJsonRequest(GOINOUT_FACEBOOK_AUTHENTICATE ++ paramsString,paramsString,HttpUtils.TIMEOUT,属性,HttpConnection.POST?);
        Dialog.alert(RES:+响应);
        JSONObject的goinoutJsonObject =新的JSONObject(响应);
        goinoutUserJsonObject =新的JSONObject(goinoutJsonObject.getString(用户));
    }赶上(IOException异常五){
        Dialog.alert(E1:+ e.getMessage());
        e.printStackTrace();
    }赶上(JSONException E1){
        Dialog.alert(E2:+ e1.getMessage());
        e1.printStackTrace();
    }
    返回goinoutUserJsonObject;
}

这下code的大块是goinout JSON请求:

 公共静态字符串sendGoinoutJsonRequest(URL字符串,字符串数据,长超时,Hashtable的性能,字符串方法)抛出IOException    HttpConnectionFactory厂=新HttpConnectionFactory(Util.getTransportPriority());
    而(真){        HttpConnectionIOSession httpConnectionIOSession = NULL;
        尝试{            的HttpConnection的HttpConnection = factory.getHttpConnection(URL);
            如果(HttpConnection的== NULL)抛出新IOException异常();
            尝试{                httpConnection.setRequestMethod(方法);
                httpConnection.setRequestProperty(如果-Modified-Since的,1999年19点43分31秒格林尼治标准​​时间10月29日);
                httpConnection.setRequestProperty(用户代理,资料/ MIDP-2.0配置/ CLDC-1.0);
                httpConnection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
                httpConnection.setRequestProperty(接受,应用/ JSON);
                httpConnection.setRequestProperty(内容长度,data.getBytes()的长度+);
                httpConnection.setRequestProperty(内容语言,EN-US);
                httpConnection.setRequestProperty(X-边缘反code含量,无);
                枚举键= properties.keys();
                而(keys.hasMoreElements()){
                    字符串键=(字符串)keys.nextElement();
                    字符串值=(字符串)properties.get(密钥);
                    httpConnection.setRequestProperty(键,值);
                }
                为OutputStream的OutputStream = httpConnection.openOutputStream();
                为InputStream的InputStream = NULL;
                如果(时间到!= -1){                    httpConnectionIOSession =新HttpConnectionIOSession(HttpConnection的,为InputStream,OutputStream的,超时);                }
                outputStream.write(data.getBytes());
                outputStream.close();
                INT响应code = httpConnection.getResponse code();
                如果(响应code!= HttpConnection.HTTP_OK){                    如果(响应code == HttpConnection.HTTP_BAD_REQUEST){                        继续;                    }
                    如果(超时= -1&安培;!&安培; HttpUtils.TIMEOUT + 2000< = TIMEOUT_MIN){                        HttpUtils.TIMEOUT + = 2000;                    }
                    抛出新IOException异常(HTTP+响应code +的错误code);                }
                的InputStream = httpConnection.openInputStream();
                最终的ByteBuffer的ByteBuffer =新的ByteBuffer(InputStream的);
                最后弦乐反应= byteBuffer.getString();
                关闭(HttpConnection的,为InputStream,OutputStream的);                如果(超时= -1&放大器;&安培; HttpUtils.TIMEOUT ​​- 1000 GT;!= TIMEOUT_MIN){                    HttpUtils.TIMEOUT ​​- = 1000;                }
                如果(httpConnectionIOSession!= NULL)httpConnectionIOSession.interrupt();
                返回响应;            }赶上(IOException异常IOException异常){                如果(超时= -1&安培;!&安培; HttpUtils.TIMEOUT + 2000< = TIMEOUT_MIN){                    HttpUtils.TIMEOUT + = 2000;                }
                抛出IOException;
            }        }赶上(IOException异常IOException异常){            如果(超时= -1&安培;!&安培; HttpUtils.TIMEOUT + 2000< = TIMEOUT_MIN){                HttpUtils.TIMEOUT + = 2000;            }
            抛出IOException;        } {最后
            如果(httpConnectionIOSession!= NULL)httpConnectionIOSession.interrupt();
        }    }}

看,我设置的属性。如果我使用这种特性的以下内容:

  httpConnection.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
httpConnection.setRequestProperty(接受,应用/ JSON);

发生的事情是,我可以检索我的BB模拟器JSON数据,并从我的实际设备使用WiFi连接。但是,当我用真实的设备使用移动服务提供商,我总是会得到IOException异常:流闭

如果我用这个下code:

  httpConnection.setRequestProperty(内容类型,应用/ JSON);
httpConnection.setRequestProperty(接受,应用/ JSON);

我总是得到HTTP错误code 500模拟器。如果我在使用移动服务提供商的实际设备中使用该属性,code是保持,因为虽然(真)那里跑。我不知道你们能帮助我。

由于事实上,code的这个块是从Facebook API和Tumblr API获取JSON数据验证工作。我总是用这code,也没有问题。我不知道这可能是与服务器端的东西错了,还是我要补充另一个属性?谢谢你这么多。

有关HttpConnectionFactory内特要求:

 包com.hammyliem.abateify.ui.network;进口java.io.IOException异常;
进口java.io.OutputStream中;
进口java.util.Vector中;进口javax.microedition.io.Connector;
进口javax.microedition.io.HttpConnection;进口net.rim.device.api.io.http.HttpHeaders;
进口net.rim.device.api.io.http.HttpProtocolConstants;
进口net.rim.device.api.servicebook.ServiceBook;
进口net.rim.device.api.servicebook.ServiceRecord;
进口net.rim.device.api.system.Branding;
进口net.rim.device.api.system.CoverageInfo;
进口net.rim.device.api.system.DeviceInfo;
进口net.rim.device.api.system.WLANInfo;公共类HttpConnectionFactory {  公共静态最终诠释TRANSPORT_WIFI = 1;
  公共静态最终诠释TRANSPORT_BES = 2;
  公共静态最终诠释TRANSPORT_BIS = 4;
  公共静态最终诠释TRANSPORT_DIRECT_TCP = 8;
  公共静态最终诠释TRANSPORT_WAP2 = 16;
  公共静态最终诠释TRANSPORT_SIM = 32;  公共静态最终诠释TRANSPORTS_ANY = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
  公共静态最终诠释TRANSPORTS_AVOID_CARRIER = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_SIM;
  公共静态最终诠释TRANSPORTS_CARRIER_ONLY = TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;  公共静态最终诠释DEFAULT_TRANSPORT_ORDER [] = {TRANSPORT_WIFI,TRANSPORT_SIM,TRANSPORT_BIS,TRANSPORT_BES,TRANSPORT_WAP2,TRANSPORT_DIRECT_TCP};  私有静态最终诠释TRANSPORT_COUNT = DEFAULT_TRANSPORT_ORDER.length;  //私有静态ServiceRecord srMDS [],srBIS [],srWAP2 [],srWiFi [];
  私有静态ServiceRecord srWAP2 [];
  私有静态布尔serviceRecordsLoaded = FALSE;  私人诠释运[];
  私人INT lastTransport = -1;  公共HttpConnectionFactory(){
    这(0);
  }  公共HttpConnectionFactory(INT allowedTransports){
    这个(transportMaskToArray(allowedTransports));
  }  公共HttpConnectionFactory(INT transportPriority []){
    如果(!serviceRecordsLoaded){
      loadServiceBooks(假);
    }
    运输= transportPriority;
  }  公共静态字符串getUserAgent(){
    StringBuffer的SB =新的StringBuffer();
    sb.append(黑莓);
    sb.append(DeviceInfo.getDeviceName());
    sb.append(/);
    sb.append(DeviceInfo.getSoftwareVersion());
    sb.append(资料/);
    sb.append(System.getProperty(microedition.profiles));
    sb.append(配置/);
    sb.append(System.getProperty(microedition.configuration));
    sb.append(厂商ID /);
    sb.append(Branding.getVendorId());    返回sb.toString();
  }  公共静态字符串getProfile(){
    StringBuffer的SB =新的StringBuffer();
    sb.append(http://www.blackberry.net/go/mobile/profiles/uaprof/);
    sb.append(DeviceInfo.getDeviceName());
    sb.append(/);
    sb.append(DeviceInfo.getSoftwareVersion()子(0,3)); // RDF文件格式是4.5.0.rdf(不包括内部版本)
    sb.append(RDF);    返回sb.toString();
  }  公众的HttpConnection getHttpConnection(字符串的pURL){
    返回getHttpConnection(的pURL,NULL,NULL);
  }  公众的HttpConnection getHttpConnection(字符串的pURL,HttpHeaders头){
    返回getHttpConnection(的pURL,头,NULL);
  }  公众的HttpConnection getHttpConnection(字符串的pURL,字节[]数据){
    返回getHttpConnection(的pURL,空,数据);
  }  公众的HttpConnection getHttpConnection(字符串的pURL,HttpHeaders头,字节[]数据){    INT curIndex = 0;
    的HttpConnection CON = NULL;    而((CON = tryHttpConnection(的pURL,curIndex,标题,数据))== NULL){
      尝试{
        curIndex = nextTransport(curIndex);
      }赶上(HttpConnectionFactoryException E){
        e.printStackTrace();
        打破;
      } {最后
      }
    }    如果(CON!= NULL){
      setLastTransport(运输[curIndex]);
    }    返回CON;
  }  私人诠释nextTransport(INT curIndex)抛出HttpConnectionFactoryException {
    如果((curIndex&GT = 0)及及(curIndex&下; transports.length - 1)){
      返回curIndex + 1;
    }其他{
      抛出新HttpConnectionFactoryException(没有更多的提供运输。);
    }
  }  私人的HttpConnection tryHttpConnection(字符串的pURL,INT tIndex,HttpHeaders头,字节[]数据){    的HttpConnection CON = NULL;
    OutputStream的OS = NULL;    开关(运输[tIndex]){
    案例TRANSPORT_SIM:
      尝试{
        CON = getSimConnection(的pURL,FALSE);
      }赶上(IOException异常五){
      } {最后
        打破;
      }
    案例TRANSPORT_WIFI:
      尝试{
        CON = getWifiConnection(的pURL);
      }赶上(IOException异常五){
      } {最后
        打破;
      }
    案例TRANSPORT_BES:
      尝试{
        CON = getBesConnection(的pURL);
      }赶上(IOException异常五){
      } {最后
        打破;
      }
    案例TRANSPORT_BIS:
      尝试{
        CON = getBisConnection(的pURL);
      }赶上(IOException异常五){
      } {最后
        打破;
      }
    案例TRANSPORT_DIRECT_TCP:
      尝试{
        CON = getTcpConnection(的pURL);
      }赶上(IOException异常五){
      } {最后
        打破;
      }
    案例TRANSPORT_WAP2:
      尝试{
        CON = getWap2Connection(的pURL);
      }赶上(IOException异常五){
      } {最后
        打破;
      }
    }    如果(CON!= NULL){
      尝试{
        //添加页眉到连接
        如果(头!= NULL){
          INT大小= headers.size();          的for(int i = 0; I<大小;){
            串标头= headers.getPropertyKey(ⅰ);
            字符串值= headers.getPropertyValue(我++);            如果(值!= NULL){
              con.setRequestProperty(标题,值);            }
          }
        }
        // 发布数据
        如果(数据!= NULL){
          con.setRequestMethod(HttpConnection.POST);
          con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLEN codeD);
          con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,将String.valueOf(data.length));          OS = con.openOutputStream();
          os.write(数据);
        }其他{
          con.setRequestMethod(HttpConnection.GET);
        }      }赶上(IOException异常五){
        e.printStackTrace();
      }
    }    返回CON;
  }  公众诠释getLastTransport(){
    返回lastTransport;
  }  公共字符串getLastTransportName(){
    返回getTransportName(getLastTransport());
  }  私人无效setLastTransport(INT pLastTransport){
    lastTransport = pLastTransport;
  }  私人的HttpConnection getSimConnection(字符串的pURL,布尔mdsSimulatorRunning)抛出IOException
    如果(DeviceInfo.isSimulator()){
      如果(mdsSimulatorRunning){
        返回的getConnection(的pURL,deviceside = false时,NULL);
      }其他{
        返回的getConnection(的pURL; deviceside =真,NULL);
      }
    }
    返回null;
  }  私人的HttpConnection getBisConnection(字符串的pURL)抛出IOException
    如果(CoverageInfo.isCoverageSufficient(4 / * CoverageInfo.COVERAGE_BIS_B * /)){
      返回的getConnection(的pURL; deviceside = FALSE; ConnectionType = MDS-公,NULL);
    }
    返回null;
  }  私人的HttpConnection getBesConnection(字符串的pURL)抛出IOException
    如果(CoverageInfo.isCoverageSufficient(2 / * CoverageInfo.COVERAGE_MDS * /)){
      返回的getConnection(的pURL,deviceside = false时,NULL);
    }
    返回null;
  }  私人的HttpConnection getWifiConnection(字符串的pURL)抛出IOException
    如果(WLANInfo.getWLANState()== WLANInfo.WLAN_STATE_CONNECTED){
      返回的getConnection(的pURL,界面=无线上网,NULL);
    }
    返回null;
  }  私人的HttpConnection getWap2Connection(字符串的pURL)抛出IOException
    如果(CoverageInfo.isCoverageSufficient(1 / * CoverageInfo.COVERAGE_DIRECT * /)及及(srWAP2 =空)及!&放大器;!(srWAP2.length = 0)){
      返回的getConnection(的pURL:; deviceside =真; ConnectionUID =,srWAP2 [0] .getUid());
    }
    返回null;
  }  私人的HttpConnection getTcpConnection(字符串的pURL)抛出IOException
    如果(CoverageInfo.isCoverageSufficient(1 / * CoverageInfo.COVERAGE_DIRECT * /)){
      返回的getConnection(的pURL; deviceside =真,NULL);
    }
    返回null;
  }  私人的HttpConnection的getConnection(字符串的pURL,字符串transportExtras1,字符串transportExtras2)抛出IOException
    StringBuffer的fullUrl =新的StringBuffer();
    fullUrl.append(的pURL);
    如果(transportExtras1!= NULL){
      fullUrl.append(transportExtras1);
    }
    如果(transportExtras2!= NULL){
      fullUrl.append(transportExtras2);
    }
    返回(的HttpConnection)Connector.open(fullUrl.toString());
  }  公共静态无效reloadServiceBooks(){
    loadServiceBooks(真);
  }  私人静态同步无效loadServiceBooks(布尔重装){
    如果(serviceRecordsLoaded&安培;&安培;!重装){
      返回;
    }
    ServiceBook SB = ServiceBook.getSB();
    ServiceRecord [] =记录sb.getRecords();
    矢量mdsVec =新的向量();
    矢量bisVec =新的向量();
    矢量wap2Vec =新的向量();
    矢量wifiVec =新的向量();    如果(!serviceRecordsLoaded){
      的for(int i = 0; I< records.length;我++){
        ServiceRecord myRecord =记录[I]
        串CID,UID;        如果(myRecord.isValid()及&放大器;!myRecord.isDisabled()){
          CID = myRecord.getCid()与toLowerCase()。
          UID = myRecord.getUid()与toLowerCase()。
          如果((cid.indexOf(wptcp)= -1)及及(uid.indexOf(WAP2)= -1)及&放大器;!(uid.indexOf(无线)== - 1)及及(uid.indexOf(MMS)== 1)){
            wap2Vec.addElement(myRecord);
          }
        }
      }      srWAP2 =新ServiceRecord [wap2Vec.size()];
      wap2Vec.copyInto(srWAP2);
      wap2Vec.removeAllElements();
      wap2Vec = NULL;      serviceRecordsLoaded = TRUE;
    }
  }  公共静态INT [] transportMaskToArray(INT面罩){
    如果(掩模== 0){
      面膜= TRANSPORTS_ANY;
    }
    INT numTransports = 0;
    的for(int i = 0; I< TRANSPORT_COUNT;我++){
      如果((DEFAULT_TRANSPORT_ORDER [1] - 放大器;!掩模)= 0){
        numTransports ++;
      }
    }
    INT运[] =新的INT [numTransports]
    INT索引= 0;
    的for(int i = 0; I< TRANSPORT_COUNT;我++){
      如果((DEFAULT_TRANSPORT_ORDER [1] - 放大器;!掩模)= 0){
        运输机[指数++] = DEFAULT_TRANSPORT_ORDER [I]
      }
    }
    返回传输;
  }  私有静态字符串getTransportName(INT运输){
    串TNAME;
    开关(运输){
    案例TRANSPORT_WIFI:
      TNAME =WIFI;
      打破;
    案例TRANSPORT_BES:
      TNAME =BES;
      打破;
    案例TRANSPORT_BIS:
      TNAME =BIS
      打破;
    案例TRANSPORT_DIRECT_TCP:
      TNAME =TCP;
      打破;
    案例TRANSPORT_WAP2:
      TNAME =WAP2
      打破;
    案例TRANSPORT_SIM:
      TNAME =SIM卡;
      打破;
    默认:
      TNAME =未知;
      打破;
    }
    返回TNAME;
  }}


解决方案

我怀疑有除了您在事件线程中运行你的code作为可能这里有两个不同的问题由内特指出。

我不知道您是在事件线程运行,因为您的应用程序将一个应用程序无响应异常,如果你被终止。但正如内特所指出的,你会如果你尝试执行对话框关闭事件线程得到一个异常。所以,我希望一个异常无论哪种方式....

要总结报告的问题,看来你得到下列之一:
a)使用设备上的无线数据服务(运行时,连接上一个IOException,而不是无线网络)
B)的HTTP code 500与特定的首部发送数据时。这意味着服务器已经回到您的要求告诉你,它已经没有理解。那么,你是不正确地送点东西。

首先,我建议你调查IOException异常 - 基本打印出来,你得到的异常(的toString()将做到这一点)的细节。这会给你对这个问题的详细信息。有许多的选择,我猜这将是一段时间了,但想知道之前,我试图提出一个解决方案。

可以参考我回到你的previous主题:<一href=\"http://stackoverflow.com/questions/19653402/blackberry-get-error-$c$c-411\">blackberry-get-error-$c$c-411请再次阅读我的回应。

有均存在两个点的所有通信的关键,而不仅仅是411错误:


  1. 用于传输的数据的编码

  2. 使用的连接方法。

编码也许是这里的关键为500回报code。当你告诉服务器你发送JSON数据,它可能预期该数据将是UTF-8 EN codeD。但是你发送的数据不会出现如此。如果你只使用标准的Latin-1字符,那么这将不会是一个问题。如果你的JSON数据包含未包括在该字符集,则数据将无法连接codeD正确,这可能是为什么您的服务器不理解。

所以为了安全,发送JSON数据时,我建议你UTF-8 EN code(并记住所产生的字节数不一定相同字符的字符串的数量)。

另外相对于500错误code(其实任何错误code),我建议你倾倒了您收到回响应头。他们可能会确定实际返回请求的服务器。因为有其他的网关可以拒绝处理请求通过移动网络的时候 - 这可能不是你的服务器。

在总结,探讨这个问题(或任何其他网络问题),我建议你:


  1. 打印出任何异常细节你

  2. 确保你知道什么连接方式用于失败
    要求

  3. 如果你没有得到很好的回报code,倾倒了头,所以你
    找出哪些服务器实际上是给你的回报code

  4. 确保您正确连接code(字符连接code,以字节为单位)
    正在发送数据(和正确的去code字节你收到如果
    您将这些回字符)。

最后一件事。由于服务器是给你一个500 - 我建议你登录后的数据在发送前,在一个失败,您可以检查它是否正确格式化。

I have been trying to get the json response from my company's json webservice. Here is the code:

public final static String GOINOUT_HOST_NAME = "http://ec2-54-254-123-244.ap-southeast-1.compute.amazonaws.com";
public final static String GOINOUT_API_VERSION = "/api/v1";

public final static String GOINOUT_FACEBOOK_AUTHENTICATE = GOINOUT_HOST_NAME + GOINOUT_API_VERSION + "/facebook_authenticate";

public static JSONObject loginGoinoutWithFacebook(String accessToken) {
    JSONObject goinoutUserJsonObject = null;
    try {
        Hashtable params = new Hashtable();
        params.put("access_token", accessToken);
        String paramsString = StringUtil.toURLParameters(params);

        Hashtable properties = new Hashtable();
        String response = HttpUtils.sendGoinoutJsonRequest(GOINOUT_FACEBOOK_AUTHENTICATE + "?" + paramsString, paramsString, HttpUtils.TIMEOUT, properties, HttpConnection.POST);
        Dialog.alert("res: " + response);
        JSONObject goinoutJsonObject = new JSONObject(response);
        goinoutUserJsonObject = new JSONObject(goinoutJsonObject.getString("user"));
    } catch (IOException e) {
        Dialog.alert("e1: " + e.getMessage());
        e.printStackTrace();
    } catch (JSONException e1) {
        Dialog.alert("e2: " + e1.getMessage());
        e1.printStackTrace();
    }
    return goinoutUserJsonObject;
}

And this following chunk of code is the goinout json request:

public static String sendGoinoutJsonRequest(String url,String data,long timeout, Hashtable properties, String method) throws IOException {

    HttpConnectionFactory factory = new HttpConnectionFactory(Util.getTransportPriority());
    while(true) {

        HttpConnectionIOSession httpConnectionIOSession = null;
        try {

            HttpConnection httpConnection = factory.getHttpConnection(url);
            if(httpConnection == null) throw new IOException();
            try {

                httpConnection.setRequestMethod(method);
                httpConnection.setRequestProperty("If-Modified-Since","29 Oct 1999 19:43:31 GMT");
                httpConnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
                httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                httpConnection.setRequestProperty("Accept","application/json");                    
                httpConnection.setRequestProperty("Content-Length",data.getBytes().length + "");
                httpConnection.setRequestProperty("Content-Language","en-US");
                httpConnection.setRequestProperty("x-rim-transcode-content","none");
                Enumeration keys = properties.keys();
                while(keys.hasMoreElements()) {
                    String key = (String) keys.nextElement();
                    String value = (String) properties.get(key);
                    httpConnection.setRequestProperty(key, value);
                }
                OutputStream outputStream = httpConnection.openOutputStream();
                InputStream inputStream = null;
                if(timeout != -1) {

                    httpConnectionIOSession = new HttpConnectionIOSession(httpConnection,inputStream,outputStream,timeout);

                }
                outputStream.write(data.getBytes());
                outputStream.close();
                int responseCode = httpConnection.getResponseCode();
                if(responseCode != HttpConnection.HTTP_OK) {

                    if(responseCode == HttpConnection.HTTP_BAD_REQUEST) {

                        continue;

                    }
                    if(timeout != -1 && HttpUtils.TIMEOUT + 2000 <= TIMEOUT_MIN) {

                        HttpUtils.TIMEOUT += 2000;

                    }
                    throw new IOException("HTTP " + responseCode + " error code.");

                }
                inputStream = httpConnection.openInputStream();
                final ByteBuffer byteBuffer = new ByteBuffer(inputStream);
                final String response = byteBuffer.getString();
                close(httpConnection,inputStream,outputStream);

                if(timeout != -1 && HttpUtils.TIMEOUT - 1000 >= TIMEOUT_MIN) {

                    HttpUtils.TIMEOUT -= 1000;

                }
                if(httpConnectionIOSession != null) httpConnectionIOSession.interrupt();
                return response;

            } catch(IOException ioException) {

                if(timeout != -1 && HttpUtils.TIMEOUT + 2000 <= TIMEOUT_MIN) {

                    HttpUtils.TIMEOUT += 2000;

                }
                throw ioException;


            }

        } catch(IOException ioException) {

            if(timeout != -1 && HttpUtils.TIMEOUT + 2000 <= TIMEOUT_MIN) {

                HttpUtils.TIMEOUT += 2000;

            }
            throw ioException;

        } finally {
            if(httpConnectionIOSession != null) httpConnectionIOSession.interrupt();
        }

    }

}

Look at the properties that I set. If I use this following of properties:

httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Accept","application/json");

what happens is that I could retrieve the JSON data from my BB simulator, and from my real device using wifi connection. BUT, when I use REAL DEVICE using Mobile Service Provider, I will always get IOException: stream closed.

If I use this following code:

httpConnection.setRequestProperty("Content-Type","application/json");
httpConnection.setRequestProperty("Accept","application/json");   

I always get HTTP Error Code 500 in simulator. And if I use this property in the real device using mobile service provider, the code is keep running because of while(true) there. I wonder if you guys could help me out.

As a matter of fact, This chunk of code is proven work in obtaining json data from Facebook API and Tumblr API. I always use this code and has no problem. I wonder if it could be something wrong with the server side, or I should add another property??? Thank you so much.

Nate request for HttpConnectionFactory:

package com.hammyliem.abateify.ui.network;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.Branding;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.WLANInfo;

public class HttpConnectionFactory {

  public static final int TRANSPORT_WIFI = 1;
  public static final int TRANSPORT_BES = 2;
  public static final int TRANSPORT_BIS = 4;
  public static final int TRANSPORT_DIRECT_TCP = 8;
  public static final int TRANSPORT_WAP2 = 16;
  public static final int TRANSPORT_SIM = 32;

  public static final int TRANSPORTS_ANY = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
  public static final int TRANSPORTS_AVOID_CARRIER = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_SIM;
  public static final int TRANSPORTS_CARRIER_ONLY = TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;

  public static final int DEFAULT_TRANSPORT_ORDER[] = { TRANSPORT_WIFI, TRANSPORT_SIM, TRANSPORT_BIS, TRANSPORT_BES, TRANSPORT_WAP2, TRANSPORT_DIRECT_TCP };

  private static final int TRANSPORT_COUNT = DEFAULT_TRANSPORT_ORDER.length;

  // private static ServiceRecord srMDS[], srBIS[], srWAP2[], srWiFi[];
  private static ServiceRecord srWAP2[];
  private static boolean serviceRecordsLoaded = false;

  private int transports[];
  private int lastTransport = -1;

  public HttpConnectionFactory() {
    this(0);
  }

  public HttpConnectionFactory(int allowedTransports) {
    this(transportMaskToArray(allowedTransports));
  }

  public HttpConnectionFactory(int transportPriority[]) {
    if (!serviceRecordsLoaded) {
      loadServiceBooks(false);
    }
    transports = transportPriority;
  }

  public static String getUserAgent() {
    StringBuffer sb = new StringBuffer();
    sb.append("BlackBerry");
    sb.append(DeviceInfo.getDeviceName());
    sb.append("/");
    sb.append(DeviceInfo.getSoftwareVersion());
    sb.append(" Profile/");
    sb.append(System.getProperty("microedition.profiles"));
    sb.append(" Configuration/");
    sb.append(System.getProperty("microedition.configuration"));
    sb.append(" VendorID/");
    sb.append(Branding.getVendorId());

    return sb.toString();
  }

  public static String getProfile() {
    StringBuffer sb = new StringBuffer();
    sb.append("http://www.blackberry.net/go/mobile/profiles/uaprof/");
    sb.append(DeviceInfo.getDeviceName());
    sb.append("/");
    sb.append(DeviceInfo.getSoftwareVersion().substring(0, 3)); //RDF file format is 4.5.0.rdf (does not include build version)
    sb.append(".rdf");

    return sb.toString();
  }

  public HttpConnection getHttpConnection(String pURL) {
    return getHttpConnection(pURL, null, null);
  }

  public HttpConnection getHttpConnection(String pURL, HttpHeaders headers) {
    return getHttpConnection(pURL, headers, null);
  }

  public HttpConnection getHttpConnection(String pURL, byte[] data) {
    return getHttpConnection(pURL, null, data);
  }

  public HttpConnection getHttpConnection(String pURL, HttpHeaders headers, byte[] data) {

    int curIndex = 0;
    HttpConnection con = null;

    while ((con = tryHttpConnection(pURL, curIndex, headers, data)) == null) {
      try {
        curIndex = nextTransport(curIndex);
      } catch (HttpConnectionFactoryException e) {
        e.printStackTrace();
        break;
      } finally {
      }
    }

    if (con != null) {
      setLastTransport(transports[curIndex]);
    }

    return con;
  }

  private int nextTransport(int curIndex) throws HttpConnectionFactoryException {
    if ((curIndex >= 0) && (curIndex < transports.length - 1)) {
      return curIndex + 1;
    } else {
      throw new HttpConnectionFactoryException("No more transport available.");
    }
  }

  private HttpConnection tryHttpConnection(String pURL, int tIndex, HttpHeaders headers, byte[] data) {

    HttpConnection con = null;
    OutputStream os = null;

    switch (transports[tIndex]) {
    case TRANSPORT_SIM:
      try {
        con = getSimConnection(pURL, false);
      } catch (IOException e) {
      } finally {
        break;
      }
    case TRANSPORT_WIFI:
      try {
        con = getWifiConnection(pURL);
      } catch (IOException e) {
      } finally {
        break;
      }
    case TRANSPORT_BES:
      try {
        con = getBesConnection(pURL);
      } catch (IOException e) {
      } finally {
        break;
      }
    case TRANSPORT_BIS:
      try {
        con = getBisConnection(pURL);
      } catch (IOException e) {
      } finally {
        break;
      }
    case TRANSPORT_DIRECT_TCP:
      try {
        con = getTcpConnection(pURL);
      } catch (IOException e) {
      } finally {
        break;
      }
    case TRANSPORT_WAP2:
      try {
        con = getWap2Connection(pURL);
      } catch (IOException e) {
      } finally {
        break;
      }
    }

    if (con != null) {
      try {
        //add headers to connection
        if (headers != null) {
          int size = headers.size();

          for (int i = 0; i < size;) {
            String header = headers.getPropertyKey(i);
            String value = headers.getPropertyValue(i++);

            if (value != null) {
              con.setRequestProperty(header, value);

            }
          }
        }
        // post data
        if (data != null) {
          con.setRequestMethod(HttpConnection.POST);
          con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
          con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(data.length));

          os = con.openOutputStream();
          os.write(data);
        } else {
          con.setRequestMethod(HttpConnection.GET);
        }

      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return con;
  }

  public int getLastTransport() {
    return lastTransport;
  }

  public String getLastTransportName() {
    return getTransportName(getLastTransport());
  }

  private void setLastTransport(int pLastTransport) {
    lastTransport = pLastTransport;
  }

  private HttpConnection getSimConnection(String pURL, boolean mdsSimulatorRunning) throws IOException {
    if (DeviceInfo.isSimulator()) {
      if (mdsSimulatorRunning) {
        return getConnection(pURL, ";deviceside=false", null);
      } else {
        return getConnection(pURL, ";deviceside=true", null);
      }
    }
    return null;
  }

  private HttpConnection getBisConnection(String pURL) throws IOException {
    if (CoverageInfo.isCoverageSufficient(4 /* CoverageInfo.COVERAGE_BIS_B */)) {
      return getConnection(pURL, ";deviceside=false;ConnectionType=mds-public", null);
    }
    return null;
  }

  private HttpConnection getBesConnection(String pURL) throws IOException {
    if (CoverageInfo.isCoverageSufficient(2 /* CoverageInfo.COVERAGE_MDS */)) {
      return getConnection(pURL, ";deviceside=false", null);
    }
    return null;
  }

  private HttpConnection getWifiConnection(String pURL) throws IOException {
    if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
      return getConnection(pURL, ";interface=wifi", null);
    }
    return null;
  }

  private HttpConnection getWap2Connection(String pURL) throws IOException {
    if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */) && (srWAP2 != null) && (srWAP2.length != 0)) {
      return getConnection(pURL, ";deviceside=true;ConnectionUID=", srWAP2[0].getUid());
    }
    return null;
  }

  private HttpConnection getTcpConnection(String pURL) throws IOException {
    if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */)) {
      return getConnection(pURL, ";deviceside=true", null);
    }
    return null;
  }

  private HttpConnection getConnection(String pURL, String transportExtras1, String transportExtras2) throws IOException {
    StringBuffer fullUrl = new StringBuffer();
    fullUrl.append(pURL);
    if (transportExtras1 != null) {
      fullUrl.append(transportExtras1);
    }
    if (transportExtras2 != null) {
      fullUrl.append(transportExtras2);
    }
    return (HttpConnection) Connector.open(fullUrl.toString());
  }

  public static void reloadServiceBooks() {
    loadServiceBooks(true);
  }

  private static synchronized void loadServiceBooks(boolean reload) {
    if (serviceRecordsLoaded && !reload) {
      return;
    }
    ServiceBook sb = ServiceBook.getSB();
    ServiceRecord[] records = sb.getRecords();
    Vector mdsVec = new Vector();
    Vector bisVec = new Vector();
    Vector wap2Vec = new Vector();
    Vector wifiVec = new Vector();

    if (!serviceRecordsLoaded) {
      for (int i = 0; i < records.length; i++) {
        ServiceRecord myRecord = records[i];
        String cid, uid;

        if (myRecord.isValid() && !myRecord.isDisabled()) {
          cid = myRecord.getCid().toLowerCase();
          uid = myRecord.getUid().toLowerCase();
          if ((cid.indexOf("wptcp") != -1) && (uid.indexOf("wap2") != -1) && (uid.indexOf("wifi") == -1) && (uid.indexOf("mms") == -1)) {
            wap2Vec.addElement(myRecord);
          }
        }
      }

      srWAP2 = new ServiceRecord[wap2Vec.size()];
      wap2Vec.copyInto(srWAP2);
      wap2Vec.removeAllElements();
      wap2Vec = null;

      serviceRecordsLoaded = true;
    }
  }

  public static int[] transportMaskToArray(int mask) {
    if (mask == 0) {
      mask = TRANSPORTS_ANY;
    }
    int numTransports = 0;
    for (int i = 0; i < TRANSPORT_COUNT; i++) {
      if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
        numTransports++;
      }
    }
    int transports[] = new int[numTransports];
    int index = 0;
    for (int i = 0; i < TRANSPORT_COUNT; i++) {
      if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
        transports[index++] = DEFAULT_TRANSPORT_ORDER[i];
      }
    }
    return transports;
  }

  private static String getTransportName(int transport) {
    String tName;
    switch (transport) {
    case TRANSPORT_WIFI:
      tName = "WIFI";
      break;
    case TRANSPORT_BES:
      tName = "BES";
      break;
    case TRANSPORT_BIS:
      tName = "BIS";
      break;
    case TRANSPORT_DIRECT_TCP:
      tName = "TCP";
      break;
    case TRANSPORT_WAP2:
      tName = "WAP2";
      break;
    case TRANSPORT_SIM:
      tName = "SIM";
      break;
    default:
      tName = "UNKNOWN";
      break;
    }
    return tName;
  }

}

解决方案

I suspect there are two different problems here in addition to the possibility that you are running your code on the Event Thread as pointed out by Nate.

I am not sure that your are running on the Event Thread because your application will be terminated with a Application Not Responding exception if you were. But as Nate points out, you will get an Exception if you try to execute a Dialog off the Event Thread. So I would expect an Exception either way....

To summarise the reported problems, it seems that you get one of the following: a) an IOException on the connection when running using the Wireless data service on device (as opposed to WiFi) b) an HTTP code 500 when sending the data with a specific header. This means a Server has returned your request telling you that it has not understood it. So you are sending something incorrectly.

First I suggest you investigate the IOException - basically print out the detail of the exception that you get (toString() will do it). This will give you more detail on the problem. There are a number of choices, I'm guessing it will be a time out, but would like to know before I attempt to suggest a solution.

Can I refer to back to your previous Thread : blackberry-get-error-code-411 Please read my response again.

There were two points in there that are critical to all communications, not just the 411 error:

  1. The encoding used for the data transmitted
  2. The connection method used.

The encoding is perhaps key here for the 500 return code. When you tell the server you are sending JSON data it probably expects that the data will be UTF-8 encoded. However the data you send does not appear to be. If you are using just the standard Latin-1 characters then this will not be a problem. If your JSON data contains characters not included in that character set, then the data will not be encoded correctly and this may be why your Server does not understand it.

So for safety, when sending JSON data, I suggest you UTF-8 encode it (and remember that the number of bytes generated is NOT necessarily the same as the number of characters in the String).

Further with respect to the 500 error code (in fact any error code), I recommend that you dump out the headers on the response you receive back. They will probably identify the Server that actually returned the request. It may not be your Server - when processing over a mobile network as there are other gateways involved that can reject requests.

In summary, to investigate this problem (or any other network problem) I suggest you:

  1. Print out the detail from any Exceptions you get
  2. Make sure you know what connection method is used for the failing request
  3. If you do not get a good return code, dump out the headers so you find out which Server actually gave you the return code
  4. Make sure you correctly encode (character encode to bytes) the data you are sending (and correct decode bytes you are received if you convert these back to characters).

One final thing. Since the Server is giving you a 500 - I suggest you log the post data before you send it, on a failure, you can check that it is properly formatted.

这篇关于黑莓OS 5 - 7 - 试图让JSON响应,并得到错误code 500的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆