我编写了一个程序,将JSON
从我的Android设备发送到我的服务器(XAMPP)。我使用表单测试了我的PHP代码,并且它正确地接收了数据。
另一方面,我的应用程序不向我的服务器发送任何数据。执行var_dump($_POST)
会在服务器端返回array(0)
。
这是我的安卓代码:
public BackGround(Context context){
this.context=context;
}
@Override
protected String doInBackground(String... params){
String location_url ="http://192.168.1.90/server_connection.php";
try{
URL url1=new URL(location_url);
HttpURLConnection httpURLConnection =(HttpURLConnection)url1.openConnection();
httpURLConnection.setRequestMethod("POST");
// httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept", "application/json");
OutputStream stream_upload=httpURLConnection.getOutputStream();
BufferedWriter buffer_writer=new BufferedWriter(new OutputStreamWriter(stream_upload,"UTF-8"));
String PostData= URLEncoder.encode(String.valueOf(params));
buffer_writer.write(PostData);
buffer_writer.flush();
buffer_writer.close();
stream_upload.close();
int HttpResult = httpURLConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
InputStream stream_dawnload = httpURLConnection.getInputStream();
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(stream_dawnload, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferreader.readLine()) != null) {
result += line;
}
bufferreader.close();
stream_upload.flush();
stream_dawnload.close();
httpURLConnection.disconnect();
return result;
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
我使用此代码发送数据,其中send_json
是我的JSON
对象:
backGround.execute(String.valueOf(send_json));
我认为问题是由JSON
对象未正确插入POST
请求正文引起的。
我知道有类似问题的问题,但没有一个解决方案帮助过我。
我感谢任何帮助。
答案 0 :(得分:0)
这里有几点你应该注意。
首先,正如您所提到的,问题似乎主要是因为您的JSON
数据未正确格式化为您的请求。您正在将数据传递给具有AsyncTask
参数的varargs
doInBackground(String... params).
:String
这会将您在调用execute(send_json)
时传递的String[]
对象转换为一个String.valueOf(params)
个对象。调用AsyncTask
不会返回与您最初传递给String
的数据类似的内容,而是返回包含您的数据的HTTP
数组的文本表示。
其次,我强烈建议您使用第三方库来为您处理网络代码。为了正确管理HTTP
连接,您必须编写的代码既不简单也不简洁。那里有更好的选择。 OkHttp是一个很好的例子,我强烈建议您使用它。
顺便说一下,我并不劝你知道如何在java / android中创建和管理function firstNonRepeatingLetter(s) {
//input string
//return first character that doesn't repeat anywhere else.
//parent for loop points to the char we are analyzing
//child for loop iterates over the remainder of the string
//if child for loop doesnt find a repeat, return the char, else break out of the child for loop and cont
if (s.length == 1) { return s;}
parent_loop:
for (var i = 0; i < s.length - 1; i++){ //parent loop
var elem = s[i];
child_loop:
for (var j = i + 1; j < s.length; j++){
if (elem == s[j]){
break child_loop;
}
}
return s[i];
}
return "";
}
console.log(firstNonRepeatingLetter('stress')); // should output t, getting s.
连接。您绝对应该尝试了解发送和接收数据时发生的情况。我只是说你不需要自己处理所有这些复杂性,因为有些库可以做得非常好。
答案 1 :(得分:0)
阅读this question's solution后,我编辑了我的代码:
首先,我从我的服务中删除了backGround.execute(String.valueOf(send_json));
,并将vriables作为参数发送到asyncTask,如下所示:
backGround.execute(String.valueOf(mylocation.getLatitude()),String.valueOf(mylocation.getLongitude()));
然后在asyncTask类中创建我的json对象。 这是我的doInbackground的代码:
@Override
protected String doInBackground(String... params){
String location_url ="http://192.168.1.90/connection.php";
try{
URL url1=new URL(location_url);
HttpURLConnection httpURLConnection =(HttpURLConnection)url1.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
OutputStream stream_upload=httpURLConnection.getOutputStream();
BufferedWriter buffer_writer=new BufferedWriter(new OutputStreamWriter(stream_upload,"UTF-8"));
JSONObject obj = new JSONObject();
try {
obj.put("Latitude", params[0]);
obj.put("Longitude", params[1]);
}catch (JSONException e){
e.printStackTrace();
}
httpURLConnection.connect();
buffer_writer.write(obj.toString());
buffer_writer.flush();
buffer_writer.close();
stream_upload.close();
int status = httpURLConnection.getResponseCode();
if(status ==httpURLConnection.HTTP_OK) {
InputStream stream_dawnload = httpURLConnection.getInputStream();
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(stream_dawnload, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferreader.readLine()) != null) {
result += line;
}
bufferreader.close();
stream_upload.flush();
stream_dawnload.close();
httpURLConnection.disconnect();
return result;
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
并且最重要的一点是:如果你想将json对象发送到服务器,你应该添加这个代码:
$json = file_get_contents('php://input');
echo (file_get_contents('php://input'));//for being aware of what is in the object.
$request = json_decode($json, true);
并使用json的值:
$location_lat=$request['Latitude'];
$location_long=$request['Longitude'];
还有一件事,我尝试了$location_lat=$_POST['Latitude']
,并且我再次提出了这个错误:未定义的索引。因此我使用了json对象,这种方法不正确。
希望有用。