如何使用 post 将 json 对象发送到网络服务器
How to send json object to the webserver using post
我想将 json 对象发送到我的网络服务器。我对以前版本的代码做了一些更改,我在其中将字符串发送到我的网络服务器。但它不适用于发送对象。请帮忙!
package com.digitalapplication.eventmanager;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class BackgroundTask extends AsyncTask<JSONObject,Void,String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(JSONObject... params) {
String inserturl="http://192.168.10.4/webapp/register.php";
String method="register";
if(method.equals("register"))
{
try {
URL url=new URL(inserturl);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
bufferedWriter.write(params.toString());
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS=httpURLConnection.getInputStream();
IS.close();
return "Data Saved in server...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "not saved in server";
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result,Toast.LENGTH_SHORT).show();
}
}
return "not saved in server";
}
这里是对后台任务的调用class
BackgroundTask backgroundTask=new BackgroundTask(this);
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("gid","asd");
jsonObject.put("uid","asdd");
jsonObject.put("name","assgd");
jsonObject.put("phone","agssd");
} catch (JSONException e) {
e.printStackTrace();
}
backgroundTask.execute(jsonObject);
这里是服务器端 php 脚本。
init.php
<?php
$db_name="eventmanager";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con=mysqli_connect($server_name, $mysql_user,$mysql_pass,$db_name);
if(!$con){
//echo"Connection Error...".mysqli_connect_error();
}
else{
//echo"<h3>Connection success....</h3>";
}
?>
和
register.php
<?php
require "init.php";
$obj = $_POST["obj"];
$args = json_decode($obj, true);
foreach($args as $key=>$field){
$gid = $field["gid"];
$uid = $field["uid"];
$name = $field["name"];
$phone = $field["phone"];
$sql_query="insert into groups values('$gid','$uid','$name','$phone');";
mysqli_query($con,$sql_query);
}
?>
我们需要更多,您看到的错误是什么?
如果您发现您正在使用省略号作为参数并对其调用 toString,请进行编辑。那只会给你一个像 [Ljava.lang.String;@659e0bfd 这样的输出,这是无效的 json。尝试
params[0].toString()
看看它是否有效。
尝试在您的 AsyncTask
中使用此方法,这是一个功能示例。
// ......
private static final String USER_AGENT = "Mozilla/5.0";
public static String sendPost(String url, String data) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept","*/*");
con.setRequestProperty("Content-Type","application/json");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
data = null;
System.out.println("\nSending 'POST' request to URL : " + url);
InputStream it = con.getInputStream();
InputStreamReader inputs = new InputStreamReader(it);
BufferedReader in = new BufferedReader(inputs);
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Server says : " + response.toString());
return response.toString();
}
您的代码看起来不错,但让我们尝试一下。如果失败,则问题出在您的服务器上。
如果您的服务器中有任何输出,请 post 它。或者您也可以在数据库插入之前打印 php 脚本中的值,以查看这些值是否真的到达了。
终于找到解决办法了。我缺少以下代码行,这些代码将在将数据发送到服务器之前对其进行编码。
String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");
bufferedWriter.write(data);
我想将 json 对象发送到我的网络服务器。我对以前版本的代码做了一些更改,我在其中将字符串发送到我的网络服务器。但它不适用于发送对象。请帮忙!
package com.digitalapplication.eventmanager;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class BackgroundTask extends AsyncTask<JSONObject,Void,String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(JSONObject... params) {
String inserturl="http://192.168.10.4/webapp/register.php";
String method="register";
if(method.equals("register"))
{
try {
URL url=new URL(inserturl);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
bufferedWriter.write(params.toString());
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS=httpURLConnection.getInputStream();
IS.close();
return "Data Saved in server...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "not saved in server";
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result,Toast.LENGTH_SHORT).show();
}
}
return "not saved in server";
}
这里是对后台任务的调用class
BackgroundTask backgroundTask=new BackgroundTask(this);
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("gid","asd");
jsonObject.put("uid","asdd");
jsonObject.put("name","assgd");
jsonObject.put("phone","agssd");
} catch (JSONException e) {
e.printStackTrace();
}
backgroundTask.execute(jsonObject);
这里是服务器端 php 脚本。
init.php
<?php
$db_name="eventmanager";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con=mysqli_connect($server_name, $mysql_user,$mysql_pass,$db_name);
if(!$con){
//echo"Connection Error...".mysqli_connect_error();
}
else{
//echo"<h3>Connection success....</h3>";
}
?>
和
register.php
<?php
require "init.php";
$obj = $_POST["obj"];
$args = json_decode($obj, true);
foreach($args as $key=>$field){
$gid = $field["gid"];
$uid = $field["uid"];
$name = $field["name"];
$phone = $field["phone"];
$sql_query="insert into groups values('$gid','$uid','$name','$phone');";
mysqli_query($con,$sql_query);
}
?>
我们需要更多,您看到的错误是什么?
如果您发现您正在使用省略号作为参数并对其调用 toString,请进行编辑。那只会给你一个像 [Ljava.lang.String;@659e0bfd 这样的输出,这是无效的 json。尝试
params[0].toString()
看看它是否有效。
尝试在您的 AsyncTask
中使用此方法,这是一个功能示例。
// ......
private static final String USER_AGENT = "Mozilla/5.0";
public static String sendPost(String url, String data) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept","*/*");
con.setRequestProperty("Content-Type","application/json");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
data = null;
System.out.println("\nSending 'POST' request to URL : " + url);
InputStream it = con.getInputStream();
InputStreamReader inputs = new InputStreamReader(it);
BufferedReader in = new BufferedReader(inputs);
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Server says : " + response.toString());
return response.toString();
}
您的代码看起来不错,但让我们尝试一下。如果失败,则问题出在您的服务器上。
如果您的服务器中有任何输出,请 post 它。或者您也可以在数据库插入之前打印 php 脚本中的值,以查看这些值是否真的到达了。
终于找到解决办法了。我缺少以下代码行,这些代码将在将数据发送到服务器之前对其进行编码。
String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");
bufferedWriter.write(data);