【问题标题】:Android - How to convert the content of a url to stringAndroid - 如何将 url 的内容转换为字符串
【发布时间】:2014-12-24 17:12:37
【问题描述】:

我正在尝试转换 URL 的内容并将其用作字符串来创建一个 toast,所有这些都由一个按钮调用。

@Override
public void onClick(View arg0) {
    String ExampleURL = ("http://pastebin.com/raw.php?i=ty0h7cS2");
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new httpGet(ExampleURL);
    HttpResponse response = null;
    try {
        response = httpClient.execute(get);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String ExampleURLContent = null;
    try {
        ExampleURLContent = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(getApplicationContext(), "10 + 10 = " + ExampleURLContent, Toast.LENGTH_SHORT).show();
}

它可以编译,但是单击按钮会强制关闭。日志猫:

 java.lang.NullPointerException: Attempt to invoke virtual method
 'boolean java.net.URI.isAbsolute()' on a null object reference
             at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496)
             at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
             at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
             at de.dotwee.kwsolver.MainActivity$1.onClick(MainActivity.java:54)

             that is this line --> (response = httpClient.execute(get);)

             at android.view.View.performClick(View.java:4756)
             at android.view.View$PerformClick.run(View.java:19749)
             at android.os.Handler.handleCallback(Handler.java:739)
             at android.os.Handler.dispatchMessage(Handler.java:95)
             at android.os.Looper.loop(Looper.java:135)
             at android.app.ActivityThread.main(ActivityThread.java:5221)
             at java.lang.reflect.Method.invoke(Native Method)
             at java.lang.reflect.Method.invoke(Method.java:372)
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

有什么帮助吗?另外,有没有更简单、代码更少的方法?

【问题讨论】:

标签: java android


【解决方案1】:

试试这个

String ExampleURLContent = null;
   try {
          if(response != null){
          ExampleURLContent = EntityUtils.toString(response.getEntity());
       }
   } catch (IOException e) {
    e.printStackTrace();
   }

【讨论】:

  • 仍然强制关闭在线response = httpClient.execute(get);
  • 你是否在 manifest 中添加了 android.permission.INTERNET 权限和 android.permission.ACCESS_NETWORK_STATE 权限。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多