简体   繁体   English

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

[英]org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused

Im trying to send the location (latitude, longitude) of an android user to a MySQL database with http post requests but get the following errors when i run the program: 我试图通过http发布请求将Android用户的位置(纬度,经度)发送到MySQL数据库,但是在运行程序时出现以下错误:

W/System.err: Followed by: W / System.err:后跟:

Errors: 错误:

E/Buffer Error: Error converting result java.lang.NullPointerException E / Buffer错误:转换结果java.lang.NullPointerException时出错

E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of E / JSON解析器:解析数据org.json.JSON异常:输入的字符0的结尾

Logcat: logcat的:

Logcat after changing "localhost" to my IP 将“ localhost”更改为我的IP后的Logcat

Logcat after changing "localhost" to my IP 将“ localhost”更改为我的IP后的Logcat

05-15 21:03:52.905 28777-28777/? 05-15 21:03:52.905 28777-28777 /? E/Zygote: isWhitelistProcess - Process is Whitelisted E /合子:isWhitelistProcess-进程被列入白名单

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

Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory 无法打开文件-/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: 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: 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;

}
}

php code for updating and inserting into MySQL database: 用于更新和插入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);
}

}

?>

if your server still on local you should using ip address instead localhost for example : 如果您的服务器仍位于本地,则应使用ip地址代替localhost,例如:

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

note: change 192.168.1.4 to your local ip address and make sure your phone and pc connected to same network. 注意:将192.168.1.4更改为您的本地IP地址,并确保您的手机和PC连接到同一网络。

is your php server host in your computer? 您的PHP服务器主机在您的计算机中吗? If so, you should use this 如果是这样,您应该使用此

https://ngrok.com/ https://ngrok.com/

so you'll make a tunnel to your server app. 因此您将建立通往服务器应用程序的通道。 your external machine is not a "local" host for your Android app 您的外部计算机不是您的Android应用的“本地”主机

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:请求中的异常:org.apache.http.conn.HttpHostConnectException:与http:// ********:80的连接被拒绝 - ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://********:80 refused Android Studio错误org.apache.http.conn.HttpHostConnectException:拒绝与http://10.0.2.2:8080的连接 - Android Studio error org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused org.apache.http.conn.HttpHostConnectException:连接到127.0.0.1:7055 [/127.0.0.1]失败:连接被拒绝:connect - org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 [/127.0.0.1] failed: Connection refused: connect Selenium 3.7:geckodriver:WebDriverException:org.apache.http.conn.HttpHostConnectException连接被拒绝 - Selenium 3.7 : geckodriver : WebDriverException: org.apache.http.conn.HttpHostConnectException Connection Refused org.apache.http.conn.HttpHostConnectException:连接到127.0.0.1:7055 - org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 线程“ main” org.apache.http.conn.HttpHostConnectException中的异常:连接到//失败:连接超时:connect - Exception in thread “main” org.apache.http.conn.HttpHostConnectException: Connect to // failed: Connection timed out: connect 在jmeter中收到错误“响应代码:非HTTP响应代码:org.apache.http.conn.HttpHostConnectException” - Getting an error “Response code: Non HTTP response code: org.apache.http.conn.HttpHostConnectException” in jmeter 从Eclipse访问URL时获取org.apache.http.conn.HttpHostConnectException - Getting org.apache.http.conn.HttpHostConnectException while accessing a URL from Eclipse GitLab Runner 不一致:exec-maven-plugin:1.6.0:java org.apache.http.conn.HttpHostConnectException - GitLab Runner Inconsistency: exec-maven-plugin:1.6.0:java org.apache.http.conn.HttpHostConnectException 引起:com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException:org.apache.http.conn.HttpHostConnectException:微服务 - Caused by: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: org.apache.http.conn.HttpHostConnectException: Microservices
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM