Android OutputStream os = conn.getOutputStream();抛出异常

时间:2017-03-24 22:33:20

标签: android httpurlconnection outputstream

我制作一个Android应用程序,我想将数据发送到服务器。我已经设法从服务器读取数据。但现在我有问题将数据发送到服务器。

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;


public class newCategoryActivity extends Activity {

private String name;
private Button btn_saveCategory;
private EditText editKategoryName;

private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_category);
    btn_saveCategory = (Button) findViewById(R.id.btn_saveCategory);
    editKategoryName = (EditText) findViewById(R.id.editKategoryName);


    btn_saveCategory.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            name = editKategoryName.getText().toString();

            Toast.makeText(newCategoryActivity.this, "Button gedrückt " + name,
                    Toast.LENGTH_LONG).show();

            String strUrl = "http://url.de/add_new_category.php";

            HashMap<String, String> paramsAsses = new HashMap<String, String>();
            paramsAsses.put("name", name);


            String responseServer = performPostCall(strUrl, paramsAsses);

            try {
                JSONObject myJson = new JSONObject(responseServer);

                int success = myJson.optInt("success");
                String msg = myJson.optString("message");

                if(success == 1) {
                    Toast.makeText(newCategoryActivity.this, msg, Toast.LENGTH_LONG).show();

                    finish();
                } else {
                    Toast.makeText(newCategoryActivity.this, "Fehler!!\n" +  msg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
}


public String  performPostCall(String requestURL, HashMap<String, String> postDataParams) {

    Toast.makeText(newCategoryActivity.this, "1. Fkt performPostCall",
           Toast.LENGTH_LONG).show();

    URL url;
    String response = "";
    try {
        Toast.makeText(newCategoryActivity.this, "Request URL " + requestURL,
                Toast.LENGTH_LONG).show();
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // TODO >> Exception
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

        writer.write(getPostDataString(postDataParams));


        writer.flush();
        writer.close();

        os.close();

        int responseCode = conn.getResponseCode();

        Toast.makeText(newCategoryActivity.this, responseCode,
                Toast.LENGTH_LONG).show();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;

            Toast.makeText(newCategoryActivity.this, "Server erreicht ",
                    Toast.LENGTH_LONG).show();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
            Toast.makeText(newCategoryActivity.this, "Server nicht erreichbar", Toast.LENGTH_LONG).show();
        }
    } catch (SocketTimeoutException e) {
        Toast.makeText(newCategoryActivity.this, "Server nicht erreichbar", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(newCategoryActivity.this, "Error", Toast.LENGTH_LONG).show();
    }

    return response;
}


private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {

    Toast.makeText(newCategoryActivity.this, "2 Fkt. getPostDataString", Toast.LENGTH_LONG).show();
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}

}

我不确定我做错了什么。我正在做很多搜索,以找出如何做一个简单的帖子,并尽我所能。

此时代码似乎崩溃

OutputStream os = conn.getOutputStream();

此时代码会弹到此代码段中的最后一个catch区域。

catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(newCategoryActivity.this, "Error", Toast.LENGTH_LONG).show();
    }

PHP-接口

<?php
require 'dbConnect.php';
$sql = "Insert into data_category (categoryname) VALUES (?);";
$name = mysqli_real_escape_string($link,$_POST['name']);
$response = array(); //JSON Response
if(empty($name)){
  $response['success'] = 0;
  $response['message'] = "Bitte geben Sie einen Namen ein";

  echo json_encode($response);
} 
else {
  $stmt = $link->prepare($sql);
  $stmt->bind_param('issss',$name);
  if($stmt==false){
    trigger_error("Fehler im SQL-Befehl.");
  }

  if($stmt->execute()){
    $response['success'] = 1;
    $response['message'] = "Die neue Kategorie wurden angelegt!";
    echo json_encode($response);

  } else {
    $response['success'] = 0;
    $response['message'] = "Hoppla, da ist was schief gegangen :/";
    echo json_encode($response);
  }
}
 ?>

我使用三星S6智能手机,Android版本6.0.1和API 23进行测试。

我对此问题的了解是:

•网址确实正确

•我还拥有网络访问权限

  

•在调试模式中,我得到的信息是conn属性有信息,但以下属性都是null:

     

“headshake”,“httpEngine”,“httpEngineFailure”,“responseHeaders”,“route”,“responseMessage”,“contentType”

     

•在调试模式中,我得到的信息是:“allowUserInteraction”,“connected”属性的值为“false”。

     

•在调试模式中我得到的信息是,属性:&gt;“fixedContentLength”,“chunkLength”,“HttpURLConnection.fixedContentLength”,“fixedContentLengthLong”,“responseCode”具有该值“-1”

这些价​​值观的原因是什么?

我得到以下 logcat

错误:

03-24 23:06:47.992 24587-24587/? E/Zygote: v2
03-24 23:06:48.002 24587-24587/? E/Zygote: accessInfo : 0

的信息:

03-24 23:06:58.242 24587-24587/com.animalshelterassistent.app     I/InjectionManager: dispatchOnViewCreated > Target : com.animalshelterassistent.app.newCategoryActivity isFragment :false
03-24 23:06:58.372 24587-24587/com.animalshelterassistent.app I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@52d6e7 time:41209838
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err: android.os.NetworkOnMainThreadException
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:482)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:465)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:447)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:353)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.animalshelterassistent.app.newCategoryActivity.performPostCall(newCategoryActivity.java:115)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.animalshelterassistent.app.newCategoryActivity$1.onClick(newCategoryActivity.java:70)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.view.View.performClick(View.java:5702)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.widget.TextView.performClick(TextView.java:10888)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.view.View$PerformClick.run(View.java:22541)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.Looper.loop(Looper.java:158)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7229)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
03-24 23:07:02.252 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err: org.json.JSONException: End of input at character 0 of 
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err:     at com.animalshelterassistent.app.newCategoryActivity$1.onClick(newCategoryActivity.java:73)
03-24 23:07:02.262 24587-24587/com.animalshelterassistent.app W/System.err:     at android.view.View.performClick(View.java:5702)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at android.widget.TextView.performClick(TextView.java:10888)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at android.view.View$PerformClick.run(View.java:22541)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at android.os.Looper.loop(Looper.java:158)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7229)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
03-24 23:07:02.272 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #1 mView = android.widget.LinearLayout{85bf2aa V.E...... ......I. 0,0-0,0}
03-24 23:07:02.402 24587-24827/com.animalshelterassistent.app D/mali_winsys: new_window_surface returns 0x3000,  [810x176]-format:1

                                                                         [         03-24 23:07:02.442 24587:24839 E/         ]
                                                                         g2d stretchFimgApi_v5 function does not exist

                                                                         [     03-24 23:07:02.442 24587:24839 E/         ]
                                                                         [JM] stretchFimgApi might be v4.
03-24 23:07:02.462 24587-24827/com.animalshelterassistent.app V/RenderScript: 0x7f78810000 Launching thread(s), CPUs 8
03-24 23:07:02.482 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
03-24 23:07:05.732 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #3 mView = null
03-24 23:07:05.752 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #1 mView = android.widget.LinearLayout{c924e9b V.E...... ......I. 0,0-0,0}
03-24 23:07:05.802 24587-24827/com.animalshelterassistent.app D/mali_winsys: new_window_surface returns 0x3000,  [770x176]-format:1
03-24 23:07:05.802 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
03-24 23:07:09.252 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #3 mView = null
03-24 23:07:09.262 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #1 mView = android.widget.LinearLayout{520e238 V.E...... ......I. 0,0-0,0}
03-24 23:07:09.302 24587-24827/com.animalshelterassistent.app D/mali_winsys: new_window_surface returns 0x3000,  [1336x249]-format:1
03-24 23:07:09.312 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
03-24 23:07:12.762 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #3 mView = null
03-24 23:07:12.782 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #1 mView = android.widget.LinearLayout{33d9211 V.E...... ......I. 0,0-0,0}
03-24 23:07:12.822 24587-24827/com.animalshelterassistent.app D/mali_winsys: new_window_surface returns 0x3000,  [981x176]-format:1
03-24 23:07:12.822 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
03-24 23:07:16.282 24587-24587/com.animalshelterassistent.app D/ViewRootImpl: #3 mView = null

您有没有想法,这个错误的原因是什么?

非常感谢你的帮助...

1 个答案:

答案 0 :(得分:0)

您应该在新线程而不是主线程中执行post调用。

Android不允许在主线程中使用网络接口。

您可以简单地将performPostCall定义为Runnable任务。或者定义一个类扩展AsyncTask。