org.apache.http.conn.HttpHostConnectException:连接到http:// localhost被拒绝

时间:2018-05-15 20:10:46

标签: java android mysql database post

我试图通过http post请求将android用户的位置(纬度,经度)发送到MySQL数据库,但在运行程序时出现以下错误:

W/System.err: 其次是:

错误:

  

E / Buffer Error:转换结果java.lang.NullPointerException

时出错      

E / JSON Parser:解析数据时出错org.json.JSONException:

字符0的输入结束

logcat的:

Logcat after changing "localhost" to my IP

Logcat after changing "localhost" to my IP

  

05-15 21:03:52.905 28777-28777 /? E / Zygote:isWhitelistProcess - Process is Whitelisted

     

05-15 21:03:52.906 28777-28777 /? E / libpersona:scanKnoxPersonas

     

无法打开文件 - /data/system/users/0/personalist.xml - 没有这样的文件或目录

Main_Activity:

import android.os.StrictMode;
import android.util.Log;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import android.Manifest;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.indooratlas.android.sdk.IALocation;
import com.indooratlas.android.sdk.IALocationListener;
import com.indooratlas.android.sdk.IALocationManager;
import com.indooratlas.android.sdk.IALocationRequest;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

JSONParser jsonParser = new JSONParser();

IALocationManager mLocationManager;
IALocationListener mLocationListener = new IALocationListener() {
    @Override
    public void onLocationChanged(IALocation iaLocation) {
        TextView txtLoc = (TextView) findViewById(R.id.textView);
        txtLoc.setText(String.valueOf(iaLocation.getLongitude() + ", " + 
iaLocation.getLatitude()));

        // build HTTP POST request to send these data to the database
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        String deviceId = "1";
        params.add(new BasicNameValuePair("deviceId", deviceId));
        System.out.println("DEVICE ID " + deviceId);

        params.add(new BasicNameValuePair("latitude", 
Double.toString(iaLocation.getLongitude())));
        System.out.println("Latitude + " + iaLocation.getLongitude());

        params.add(new BasicNameValuePair("longitude", 
Double.toString(iaLocation.getLatitude())));
        System.out.println("Longitude+ " + iaLocation.getLatitude());


jsonParser.makeHttpRequest("http://localhost/android_connect/update11.php", 
"POST", params);
    }







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

    }

};
private final int CODE_PERMISSIONS = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    TextView txtLoc = (TextView) findViewById(R.id.textView);

    mLocationManager = IALocationManager.create(this);


    String[] neededPermissions = {
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN



    };
    ActivityCompat.requestPermissions(this, neededPermissions, 
CODE_PERMISSIONS);
    StrictMode.ThreadPolicy policy = new 
StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);

}
public void onRequestPermissionsResult(int requestCode, String[] 
permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, 
grantResults);

    //Handle if any of the permissions are denied, in grantResults
}


protected void onResume() {
    super.onResume();
    mLocationManager.requestLocationUpdates(IALocationRequest.create(), 
mLocationListener);

}

protected void onPause() {
    mLocationManager.removeLocationUpdates(mLocationListener);
    super.onPause();
}

protected void onDestroy() {

   mLocationManager.destroy();
   super.onDestroy();
}
}

ANDROID_MANIFEST:

<?xml version="1.0" encoding="utf-8"?>

<uses-feature android:name="android.hardware.sensor.accelerometer"
    android:required="true" />
<uses-feature android:name="android.hardware.sensor.compass"
    android:required="true" />
<uses-feature android:name="android.hardware.sensor.gyroscope"
    android:required="true" />
<uses-feature android:name="android.hardware.wifi"
    android:required="true" />

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>



<application


    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="IndoorAtlasExample"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.indooratlas.android.sdk.API_KEY"
        android:value="<API key here>"/>

    <meta-data android:name="com.indooratlas.android.sdk.API_SECRET"
        android:value="<API secret here>"/>


    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

JSONParser:

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Used to submit new IndoorAtlas readings to the MySQL server via JSON on 
the phone (this
* class) & PHP on the Web server.
*/
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}
用于更新和插入MySQL数据库的 php代码:

<?php
/*
All product details are read from HTTP Post Request
*/
// error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
// error_reporting(E_ERROR | E_PARSE);
if ($_SERVER ["REQUEST_METHOD"]=="POST"){
require'connectiontest.php';
createStudent();
}
// array for JSON response
$response = array();

function createstudent()
{

// check for required fields
if (isset($_POST['deviceId']) && isset($_POST['latitude']) && 
isset($_POST['longitude'])) {
// extract data from POST into variables
global $connect;

$deviceId = $_POST['deviceId']; 
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];

//  $time = $_POST['time'];

$query = "SELECT * FROM cord WHERE deviceId = '$deviceId';";
$result=mysqli_query($connect,$query);

$count=mysqli_num_rows($result);
if($count>0) 
{error_log("Database already has that deviceId, doing an UPDATE.", 0);
    $query = "UPDATE cord SET latitude = '$latitude', longitude = 
'$longitude' WHERE deviceId = '$deviceId';";
}
else{
error_log("Database is empty, doing an INSERT.", 0);
$query = "INSERT INTO cord (deviceId, latitude, longitude) VALUES 
('$deviceId', '$latitude', '$longitude');";

}
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);



// check if row inserted or not
if ($query) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Entry successfully inserted or updated.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Entry was not successfully inserted or 
updated.";

    // echoing JSON response
    echo json_encode($response);
}
}  else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}

}

?>

2 个答案:

答案 0 :(得分:1)

如果您的服务器仍在本地,则应使用ip地址而不是localhost 例如:

QGraphicsView::drawItems()

注意:将192.168.1.4更改为您的本地IP地址,并确保您的手机和PC连接到同一网络。

答案 1 :(得分:0)

是您计算机中的php服务器主机?如果是这样,你应该使用这个

https://ngrok.com/

这样您就可以建立到服务器应用的隧道了。你的外部机器不是本地的&#34;适用于Android应用的主机