I want to send json object to my webserver. I make some changes in previous version of code, where i was sending strings to my webserver. but it is not working for sending object. Please help!
我想将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";
}
here is call to the backgroundTask class
这里是对backgroundTask类的调用
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);
here is server side php script.
这是服务器端的PHP脚本。
init.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>";
}
?>
And
和
register.php
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);
}
?>
3 个解决方案
#1
1
We'll need more than that, whats the error you are seeing ?
我们还需要更多,你看到的错误是什么?
Edit if you see you are using ellipses as the param and calling toString on it. That will only give you an output like [Ljava.lang.String;@659e0bfd , which is not valid json. Try
如果您看到使用省略号作为参数并在其上调用toString,请进行编辑。这只会给你一个像[Ljava.lang.String; @ 659e0bfd这样的输出,这是无效的json。尝试
params[0].toString()
and see if it works.
并看看它是否有效。
#2
1
Try using this method in your AsyncTask
, this is a functional example.
尝试在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();
}
Your code looks well, but let's go to try with this. If this fails then, the problem is in your server.
你的代码看起来不错,但让我们试试吧。如果此操作失败,则问题出在服务器中。
If you have any output in your server please post it. Or you can too, print the values in your php script before the database insert, to see if really the values are arriving.
如果您的服务器中有任何输出,请发布。或者您也可以在数据库插入之前在PHP脚本中打印值,以查看值是否真的到达。
#3
0
At last I found the solution. I was missing following line of code which will encode my data before sending it to the server.
最后我找到了解决方案。我错过了以下代码行,它会在将数据发送到服务器之前对其进行编码。
String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");
bufferedWriter.write(data);
#1
1
We'll need more than that, whats the error you are seeing ?
我们还需要更多,你看到的错误是什么?
Edit if you see you are using ellipses as the param and calling toString on it. That will only give you an output like [Ljava.lang.String;@659e0bfd , which is not valid json. Try
如果您看到使用省略号作为参数并在其上调用toString,请进行编辑。这只会给你一个像[Ljava.lang.String; @ 659e0bfd这样的输出,这是无效的json。尝试
params[0].toString()
and see if it works.
并看看它是否有效。
#2
1
Try using this method in your AsyncTask
, this is a functional example.
尝试在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();
}
Your code looks well, but let's go to try with this. If this fails then, the problem is in your server.
你的代码看起来不错,但让我们试试吧。如果此操作失败,则问题出在服务器中。
If you have any output in your server please post it. Or you can too, print the values in your php script before the database insert, to see if really the values are arriving.
如果您的服务器中有任何输出,请发布。或者您也可以在数据库插入之前在PHP脚本中打印值,以查看值是否真的到达。
#3
0
At last I found the solution. I was missing following line of code which will encode my data before sending it to the server.
最后我找到了解决方案。我错过了以下代码行,它会在将数据发送到服务器之前对其进行编码。
String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");
bufferedWriter.write(data);