Http Request不适用于Java(在Android应用上)

时间:2019-12-19 19:11:05

标签: java android httprequest

现在大概一个月了,我仍在努力通过android应用发送简单的请求。尝试了几种方法,使用过的库却失败了。希望人们可能会看到我看不到的错误。应用程序在启动时崩溃。

这是我尝试的最后一个代码:

public class MainActivity extends Activity {

Handler handler2;
String result="";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyThread mt= new MyThread();
    mt.start();
}


private class MyThread extends Thread{
    @Override
    public void run() {
        Toast.makeText(MainActivity.this,"thread created",Toast.LENGTH_LONG).show();
        URL url = null;
        try {
            url = new URL("http://www.android.com/");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {                   
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                result = readStream(in);
                Toast.makeText(MainActivity.this,"success",Toast.LENGTH_LONG).show();
            } finally {
                urlConnection.disconnect();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        handler2.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
                }
            });

    }

然后有logcat:

12-19 13:59:24.989 18412 18412 E   AndroidRuntime                               Process: com.system.alt, PID: 18412
12-19 13:59:24.989 18412 18412 E   AndroidRuntime                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.system.alt/com.system.alt.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
12-19 13:59:24.989 18412 18412 E   AndroidRuntime                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)

我认为启动新线程有问题。有人可以帮忙吗?我被困住了。 :(

1 个答案:

答案 0 :(得分:0)

尝试扩展AppCompatActivity而不是Activity

...
public class MainActivity extends AppCompatActivity{
...