2017-12-11 8 views
-2

내 Android 장치에서 내 서버로 일부 지리 정보를 보내려는 POST 요청을 호출하고 싶습니다.Android - HTTP 게시 요청

내 서버는 PHP를 사용하며 PHP 스크립트를 사용하여 들어오는 모든 게시물 요청을 데이터베이스에 저장하고 싶습니다. 내 PHP 스크립트는 곱슬 곱슬 해봤을 때 잘 작동하지만 안드로이드 장치에서 일부 정보를 보내려고 할 때 네트워크 오류가 발생합니다. 여기

내 오류가 기록됩니다

다음
12-11 12:08:02.871 10241-10241/local.example.markus.geoapp E/AndroidRuntime: FATAL EXCEPTION: main 
Process: local.example.markus.geoapp, PID: 10241 
android.os.NetworkOnMainThreadException 
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448) 
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102) 
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90) 
at java.net.InetAddress.getAllByName(InetAddress.java:787) 
at com.android.okhttp.Dns$1.lookup(Dns.java:39) 
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175) 
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141) 
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83) 
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) 
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126) 
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95) 
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281) 
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258) 
at com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.getOutputStream(TrackedHttpURLConnection.java:288) 
at com.android.tools.profiler.support.network.httpurl.HttpURLConnection$.getOutputStream(HttpURLConnection$.java:212) 
at local.example.markus.geoapp.MapsListener.sendPost(MapsListener.java:121) 
at local.example.markus.geoapp.MapsListener.onLocationChanged(MapsListener.java:77) 
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:291) 
at android.location.LocationManager$ListenerTransport.-wrap0(Unknown Source:0) 
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:236) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

내 자바 코드는 내가 http://example.local/gps.php 내 PHP 스크립트에 POST 요청에 대한 몇 가지 정보를 보낼 수있는 방법

package local.example.markus.geoapp; 

import android.Manifest; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.app.ActivityCompat; 
import android.util.Log; 

import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.model.CameraPosition; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

import java.io.BufferedOutputStream; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.sql.Timestamp; 

/** 
* Created by markus on 04.12.17. 
*/ 

public class MapsListener implements LocationListener { 
// Member Variablen 
private GoogleMap googleMap; 

// Konstruktor 
public MapsListener() { 

} 

// Getter und Setter 
public GoogleMap getGoogleMap() { 
    return googleMap; 
} 

public void setGoogleMap(GoogleMap googleMap) { 
    this.googleMap = googleMap; 
} 


// Interface Methods 
@Override 
public void onLocationChanged(Location location) { 
    // Print new Latitide and Logtitude into log 
    Log.d("INFO", "New Location! Latitude: '" + location.getLatitude() + "', '" + location.getLongitude() + "'"); 

    // Define new Latitude and Logtitude object 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 

    // Add a new Marker to the Map 
    this.googleMap.addMarker(new MarkerOptions().position(latLng).title("Lat:" + location.getLatitude() + ", Lng: " + location.getLongitude())); 

    // Build ca,era position 
    CameraPosition cameraPosition = new CameraPosition.Builder() 
      .target(new LatLng(location.getLatitude(), location.getLongitude()))  // Sets the center of the map to location user 
      .zoom(17)                 // Sets the zoom 
      .bearing(0)                // Sets the orientation of the camera to north 
      .tilt(40)                 // Sets the tilt of the camera to 30 degrees 
      .build();                 // Creates a CameraPosition from the builder 

    // Animate camera to zoom to the new position with defined settings 
    this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 

    Log.d("Device ID", this.getDeviceId()); 
    this.sendPost(location); 
} 

@Override 
public void onStatusChanged(String s, int i, Bundle bundle) { 

} 

@Override 
public void onProviderEnabled(String s) { 

} 

@Override 
public void onProviderDisabled(String s) { 

} 

private String getDeviceId() { 
    if (Build.VERSION.SDK_INT <= 25) { 
     return Build.SERIAL; 
    } else { 
     return Build.getSerial(); 
    } 
} 

private void sendPost(Location location) { 
    URL url = null; 
    HttpURLConnection httpURLConnection = null; 
    OutputStream outputStream = null; 

    try{ 
     url = new URL("http://example.local"); 
     httpURLConnection = (HttpURLConnection) url.openConnection(); 

     Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 

     /*httpURLConnection.setRequestMethod("POST"); 
     httpURLConnection.setRequestProperty("d", this.getDeviceId()); 
     httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude())); 
     httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude())); 
     httpURLConnection.setRequestProperty("t", timestamp.toString()); 
     httpURLConnection.setDoOutput(true);*/ 

     outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream()); 

     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 

     writer.write(Double.toString(location.getLongitude())); 

     writer.flush(); 

     writer.close(); 

     outputStream.close(); 


     httpURLConnection.disconnect(); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
} 

?

게시물 Sending POST data in Android이 작동하지 않습니다.

+1

https://stackoverflow.com/questions/30180957/send-post-request-with-params-using-retrofit 작업을 쉽게하기 위해 개장 라이브러리를 사용하거나 Async http를 사용하여 메인 스레드에서 API를 실행하십시오. – R2R

+0

읽다? 그것은 명확하게'NetworkOnMainThreadException'을 말하고 안드로이드 참조를 확인하면 거기에 :'응용 프로그램이 주 스레드에서 네트워킹 작업을 수행하려고 할 때 던져지는 예외입니다 .' – vilpe89

답변

0

이 예외는 응용 프로그램이 주 스레드에서 네트워킹 작업을 수행하려고 할 때 발생합니다. AsyncTask에서 코드를 실행하십시오.

public class HttpPost extends AsyncTask<String, String, String> { 


    protected String doInBackground(String... args) { 
     URL url = null; 
     HttpURLConnection httpURLConnection = null; 
     OutputStream outputStream = null; 

     try{ 
      url = new URL("http://example.local"); 
      httpURLConnection = (HttpURLConnection) url.openConnection(); 

      Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 

      /*httpURLConnection.setRequestMethod("POST"); 
      httpURLConnection.setRequestProperty("d", this.getDeviceId()); 
      httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude())); 
      httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude())); 
      httpURLConnection.setRequestProperty("t", timestamp.toString()); 
      httpURLConnection.setDoOutput(true);*/ 

      outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream()); 

      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 

      writer.write(Double.toString(location.getLongitude())); 
      writer.flush(); 
      writer.close(); 
      outputStream.close(); 
      httpURLConnection.disconnect(); 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
    } 

    protected void onPostExecute(String result) { 
     //What you want to do with the result 
     //Call a callback function for instance 
     //You can also delete this method if you dont expect a result 
    } 
} 
0

게시물 Sending POST data in Android이 작동하지 않습니다.

위의 내용은 허용 된 상태에서 upvoted 상태가 아닌 다른 모든 항목에서 절대적으로 작동합니다.

점에서 만들어지는 네트워크 호출이 하나 아래 놓친

ans와 방법을 놓친 이후 분명 얻고있는 어떤 오류.

공용 클래스 CallAPI는 UI 스레드가 허용되지 않는 전화 네트워크 안드로이드이나 다른 플랫폼 플랫폼의 대부분을에서 AsyncTask를 {

을 확장합니다. 안드로이드에서 AsyncTask는 UI 스레드에서 네트워크 호출을 만드는 한 가지 방법입니다.