gpt4 book ai didi

java - org.apache.http.conn.HttpHostConnectException : Connection to http://localhost refused

转载 作者:行者123 更新时间:2023-11-29 10:14:20 26 4
gpt4 key购买 nike

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

W/System.err:随后:

错误:

E/Buffer Error: Error converting result java.lang.NullPointerException

E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of

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

Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory

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);
}

}

?>

最佳答案

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

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

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

关于java - org.apache.http.conn.HttpHostConnectException : Connection to http://localhost refused,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50358449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com