为什么在尝试使用DataOutputStream时我的应用程序崩溃

时间:2019-05-29 13:03:02

标签: java

我正在尝试创建一个使用DataOutputStream将信息发布到网页上的应用程序out = new DataOutputStream(httpURLConnection.getOutputStream()); 但是,如果我尝试这样做,它就会崩溃。

我的app / src / main / AndroidManifest.xml看起来像这样:

    

<uses-permission android:name="com.symbol.emdk.permission.EMDK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />
<uses-permission android:name="android.permission.BIND_CARRIER_MESSAGING_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <uses-library android:name="com.symbol.emdk"/>

class AsyncT extends AsyncTask<Void,Void,Void>
{
    public String info="";
    public String info2="";
    @Override
    protected Void doInBackground(Void... voids) {


        try {
            URL url = new URL("http://mypage.nu/info.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); 
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);
            httpURLConnection.setConnectTimeout(20000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); 
            //httpURLConnection.connect();
            try {
                    DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());//Something goes wrong  
            }catch(IOException e){     
                 e.printStackTrace();                    
            }
            String json="{'name':'test'}";
            out.writeBytes("x="+json);
            httpURLConnection.disconnect();
        }...

我希望我可以找回$obj = json_decode($_POST["x"], false);

但是在尝试创建DataOutputStream out = new DataOutputStream

时就会消失

1 个答案:

答案 0 :(得分:0)

您必须告诉连接要输出流。

httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);

请参见UrlConnection章节: Java