我的HttpUrlConnection有问题

时间:2018-12-05 00:42:23

标签: java android httpurlconnection

请帮助我解决这个问题:

我正在尝试从将连接到php服务的类中调用方法。它没有任何错误,但是当我运行它时,它关闭并显示消息抱歉,该应用已停止

这是主要活动:

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void hhtp(View view) throws Exception {
        result="";
        JavaHttpUrlConnectionReader con = new JavaHttpUrlConnectionReader();
        result = con.doHttpUrlConnectionAction("http://example.com/app.php");
        Toast.makeText(getApplicationContext(),"Button is clicked"+result,Toast.LENGTH_LONG).show();
    }
}

这是课程:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class JavaHttpUrlConnectionReader {

    public static void main(String[] args)
            throws Exception
    {
        new JavaHttpUrlConnectionReader();
    }
   public String doHttpUrlConnectionAction(String desiredUrl)
            throws Exception
    {
        URL url = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder;

        try
        {
            // create the HttpURLConnection
            url = new URL(desiredUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // just want to do an HTTP GET here
            connection.setRequestMethod("GET");

            // uncomment this if you want to write output to this url
            //connection.setDoOutput(true);

            // give it 15 seconds to respond
            connection.setReadTimeout(15*1000);
            connection.connect();

            // read the output from the server
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        }
        finally
        {
            // close the reader; this can throw an exception too, so
            // wrap it in another try/catch block.
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
    }
}

这是main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/http_url_request_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="hhtp"
        android:text="Checa si hay nueva Sol" />

</android.support.constraint.ConstraintLayout>

最后是php中的Web服务:

<?php
$data=$_POST['dato'];
$rsp="1";
echo $rsp;
?>

2 个答案:

答案 0 :(得分:1)

您正在对UI线程进行网络调用,这引发了异常。尝试使用AsyncTask类,然后从那里进行网络连接。

答案 1 :(得分:0)

您遇到了“主线程上的网络连接”异常! 恭喜,您现在是L2 Android开发人员:D

这是由Android操作系统强制执行的,以确保应用程序不会无响应,并确保开发人员正在异步处理工作,嗯...异步!

在此处查看基本原理-> https://developer.android.com/reference/android/os/NetworkOnMainThreadException

这里有几种解决方案的方法-AsyncTasks,Runnables,Handlers,Java Futures,Kotlin Coroutines,Rx(按复杂程度排序)。

以下是围绕此问题回答的一些类似问题:

祝你好运,如果找不到前进的路,就回这里!