2017-03-24 4 views
0

私はアンドロイドアプリケーションを作成し、私はサーバーにデータを送信したい。私はすでにサーバーからデータを読み取ることができました。しかし、今私は、サーバーにデータを送信する問題があります。Android出力ストリームos = conn.getOutputStream();例外を投げる

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 (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

でそれをテストしている:

•URLが実際に正しいこと

•ネットワークアクセスのアクセス許可もあります

• In the debug modus I get the information, that the conn attribute have information but the following attributes are all null:

"headshake", "httpEngine", "httpEngineFailure", "responseHeaders", "route", "responseMessage", "contentType"

• In the debug modus I get the information, that the attribute: "allowUserInteraction", "connected" have the value "false".

• In the debug modus I get the information, that the attribute: >"fixedContentLength", "chunkLength", "HttpURLConnection.fixedContentLength", "fixedContentLengthLong", "responseCode" have the value "-1"

その理由は何ですか?

エラー:

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

情報:私は、次のlogcat取得

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: [email protected] 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 

は、あなたのアイデアを持っている、このエラーの理由をwhat's?

+0

なぜNetworkOnMainThreadExceptionのためにGoogleを使いませんでしたか?恥! – greenapps

答えて

0

新しいスレッドの代わりに、メインスレッドにポスト呼び出しを実行する必要があります...あなたのhelppいただき、誠にありがとうございます。

Androidはメインスレッドでネットワークインターフェイスを使用することを許可していません。

実行可能タスクに対して単にperformPostCallを定義することができます。または、AsyncTaskを拡張するクラスを定義します。

+0

ありがとうございました。私は問題を解決しました。 :-) –

関連する問題