【问题标题】:Trying to create a json class in my application试图在我的应用程序中创建一个 json 类
【发布时间】:2013-08-14 19:08:01
【问题描述】:

我尝试为我的应用程序构建一个 json 类,但我不知道它为什么不起作用: http://pastebin.com/A9Wr9v0m

我需要帮助!谢谢!

【问题讨论】:

  • 究竟是什么不工作?

标签: android json class


【解决方案1】:

你想在你的 UI 线程上使用这个类吗?

如果是这样,那么它不起作用的原因是因为您不能在主 ui 线程上执行网络操作,它们需要在异步类或单独的线程中完成

【讨论】:

  • 我正在尝试制作游戏,一开始我想制作一个登录页面。
  • android 不允许您在用户界面线程上发出任何 HTTP 请求,您需要在后台线程或异步类中进行。因此您在 json 类中发出的 HTTP 请求必须放入一个新线程中
  • 你有例子吗?英语不是我的第一语言,所以我最好看一个示例代码。
  • android-developers.blogspot.co.uk/2010/07/… 该网页有一个使用异步进行 http 调用的好例子
【解决方案2】:

使用以下代码:-

  public static String getJsonData(String webServiceName,String parameter)
{  
    try  
    {

    String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
    HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");

    HttpClient hc = new DefaultHttpClient();

    HttpResponse response = hc.execute(postMethod);
    Log.i("response", ""+response.toString());
    HttpEntity entity = response.getEntity();
    final String responseText = EntityUtils.toString(entity);

    string=responseText;
    Log.i("Output", ""+responseText);
      }
      catch (Exception e) {
        // TODO: handle exception
    }

       return string;
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多