有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android HTTP Post请求

我想打一个POST请求,将一些地理信息从我的安卓设备发送到我的服务器

我的服务器使用PHP,我想使用PHP脚本将所有传入的post请求保存在我的数据库中。当我尝试使用curl时,我的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
 安卓.os.NetworkOnMainThreadException
 at 安卓.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.安卓.okhttp.Dns$1.lookup(Dns.java:39)
 at com.安卓.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
 at com.安卓.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
 at com.安卓.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
 at com.安卓.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
 at com.安卓.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
 at com.安卓.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
 at com.安卓.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
 at com.安卓.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
 at com.安卓.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
 at com.安卓.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
 at com.安卓.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
 at com.安卓.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.getOutputStream(TrackedHttpURLConnection.java:288)
 at com.安卓.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 安卓.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:291)
 at 安卓.location.LocationManager$ListenerTransport.-wrap0(Unknown Source:0)
 at 安卓.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:236)
 at 安卓.os.Handler.dispatchMessage(Handler.java:105)
 at 安卓.os.Looper.loop(Looper.java:164)
 at 安卓.app.ActivityThread.main(ActivityThread.java:6541)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.安卓.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:767)

这是我的java代码

package local.example.markus.geoapp;

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

import com.google.安卓.gms.maps.CameraUpdate;
import com.google.安卓.gms.maps.CameraUpdateFactory;
import com.google.安卓.gms.maps.GoogleMap;
import com.google.安卓.gms.maps.model.CameraPosition;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.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();
    }
}
}

如何将POST请求的相关信息发送到http://example.local/gps.php上的php脚本

postSending POST data in Android不起作用


共 (2) 个答案

  1. # 1 楼答案

    帖子Sending POST data in Android不起作用

    上述方法应该绝对有效,否则ans就不会处于被接受和被投票的状态

    由于忽略了在该ans中如何进行网络呼叫,错误变得显而易见

    你漏了一个

    public class CallAPI extends AsyncTask {

    在android或其他平台上,大多数平台也不允许网络调用ui线程。在Android中,AsyncTask是让网络取消ui线程的一种方法

  2. # 2 楼答案

    当应用程序试图在其主线程上执行网络操作时,会引发此异常。在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
        }
    }