Android JSON POST 方法
Android JSON POST Method
我是 Android 的初学者,正在开发一个应用程序,该应用程序使用 PHP 脚本从 SQL 本地主机(临时)服务器获取数据以获得所需的 table并提取字段。现在按照教程一切都很好所以我有一个 ReyclerView
和 CustomAdapter
并且正在使用 LoaderManager
所以我有一个加载器也可以在我的 Utils Class
里面执行 fetchData 方法Class 有一些方法用于制作 HttpUrlConnection
直到从我的 SQL 数据库中提取 JSON 数据并将其提取到我的模型的 List<>
(Dish.Java) 其中包含导体和 getter 方法。
但现在我正在尝试将数据发送到另一个 table 例如用于项目喜欢或评级的每个项目为此目的我创建了新的 Table 它只包含喜欢作为 INT(后来附加到带有外键的项目),因此我搜索并找到了一个 PHP 脚本(适合我获取数据的白痴情况)如下:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
require 'connection.php';
updateLikes();
}
function updateLikes(){
global $connect;
$likes = $_POST['likes'];
$query = "UPDATE likes SET likes = '$likes'";
mysqli_query($connect,$query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
如果我尝试发出 POST
请求而不是 PUT,例如 Postman
我可以更改我的 table 中的喜欢字段。但不知道如何将其添加到我的查询中
因此,例如在评分后获取 Ratingbar
的值并将其累积到喜欢字段中的服务器(我知道这很荒谬)。
我发现我可以为 HttpUrlConnection
制作 setRequestMethod
到 "POST" 并像这样使用 DataOutputStream
:
class UpdateLikes extends AsyncTask<String, Void, Void> {
String URL = "http://localhost:81/likes.php";
@Override
protected Void doInBackground(String... params) {
String jsonData = params[0];
String charset = "UTF-8";
try {
java.net.URL url = new URL(URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
//send data
DataOutputStream os = new DataOutputStream(httpURLConnection.getOutputStream());
os.writeBytes(jsonData.toString());
//OutputStream dos = httpURLConnection.getOutputStream();
//dos.write(Integer.parseInt(jsonData.toString()));
//receive & read data response
InputStream is = httpURLConnection.getInputStream();
StringBuilder result = new StringBuilder();
int byteCharacter;
while ((byteCharacter = is.read()) != -1) {
result.append((char) byteCharacter);
}
Log.d("json api", "DoUpdateProduct.doInBackground Json return: " + result);
os.flush();
is.close();
os.close();
httpURLConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
这是我在 ratingbar 侦听器中执行 AsyncTask 的代码 doInBackground
String counter = String.valueOf(rating);
Like likes = new Like(counter);
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject.put("likes",likes.likes);
jsonArray.put(jsonObject);
Log.d("json api", "Json array converted from Product: " + jsonArray.toString());
String jsonData = String.valueOf(jsonArray);
new UpdateLikes().execute(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e(MondayActivity.LOG_TAG, "Rating is:" + rating);
}
});
然后执行的事情是当我调试时我可以获得评级并将其设置到数组,建立连接但它不会更新我的数据库中的任何内容。
所以任何关于我如何实现这一点的建议,或者可能有完全另一种方法甚至重新考虑的方法,我都会感激不尽。
这是我的类所以你看看发生了什么
QuerUtils.Java
public class QueryUtils {
public static long date;
public static ArrayList<String> ls;
public QueryUtils() {
}
private static URL createUrl(String strUrl) {
URL url = null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
//TODO new
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
output.append(line);
line = bufferedReader.readLine();
}
}
return output.toString();
}
public static List<Dish> fetchData(String requestUrl) {
/* try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
URL url = createUrl(requestUrl);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Dish> dishes = extractFeatureFromJson(jsonResponse);
Log.i(LOG_TAG, "QueryUtils returns " + dishes);
return dishes;
}
private static List<Dish> extractFeatureFromJson(String jsonResponse) {
if (TextUtils.isEmpty(jsonResponse)) {
return null;
}
List<Dish> dishes = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
JSONObject jsonObject1 = null;
//dishes = new ArrayList<>();
ls = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject1 = (JSONObject) jsonArray.get(i);
if (jsonObject1 != null) {
String name = jsonObject1.getString("dish");
String daytime = jsonObject1.getString("daytime");
String dishName = jsonObject1.getString("dish");
String component = jsonObject1.getString("component");
double price = jsonObject1.getDouble("price");
String day = jsonObject1.getString("weakday");
int iconId_1 = jsonObject1.getInt("iconid_1");
int iconId_2 = jsonObject1.getInt("iconid_2");
date = jsonObject1.getLong("date");
int likesCounter = jsonObject1.getInt("likes");
String likes = String.valueOf((int) likesCounter);
Log.e(LOG_TAG, String.valueOf(date));
ls.add(jsonObject1.getString("date"));
Dish dish = new Dish(name, daytime, dishName,
component, price, day, date, iconId_1, iconId_2, likes);
dishes.add(dish);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return dishes;
}
}
DishAdapterTest.java
public class DishAdapterTest extends RecyclerView.Adapter<DishAdapterTest.ViewHolder> {
private List<Dish> dishes;
private Context context;
public DishAdapterTest(Context context, List<Dish> dishes) {
this.context = context;
this.dishes = dishes;
}
@NonNull
@Override
public DishAdapterTest.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item_dish, parent, false);
return new ViewHolder(itemView);
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
final Dish dish = dishes.get(position);
holder.daytimeTextView.setText(dish.getmDayTime());
holder.dishTextView.setText(dish.getmDish());
holder.componentTextView.setText(dish.getmComponent());
double originalPrice = dish.getmPrice();
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.GERMANY);
String price = format.format(originalPrice);
//String format2 = new DecimalFormat("#,###.00").format(dish.getmPrice());
holder.priceTextView.setText(price);
int icon_id = getIcon(dish.getmImageResId1());
holder.iconImageView.setImageResource(icon_id);
int icon_id2 = getIcon(dish.getmImageResId2());
holder.icon1ImageView.setImageResource(icon_id2);
holder.likesTextView.setText(dish.getmLikes());
holder.mRatingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Log.e(MondayActivity.LOG_TAG, "Rating is:" + rating);
}
});
}
public void setData(List<Dish> data) {
dishes.clear();
dishes.addAll(data);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
Log.i("DishAdapter Mensa ", "dishes.size() = " + dishes.size());
return dishes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// The ViewHolder design pattern
private TextView daytimeTextView;
private TextView dishTextView;
private TextView componentTextView;
private TextView priceTextView;
private ImageView iconImageView;
private ImageView icon1ImageView;
private RatingBar mRatingbar;
private TextView likesTextView;
public ViewHolder(View view) {
super(view);
this.daytimeTextView = view.findViewById(R.id.daytime_text_view);
this.dishTextView = view.findViewById(R.id.dish_text_view);
this.componentTextView = view.findViewById(R.id.component_text_view);
this.priceTextView = view.findViewById(R.id.price_text_view);
this.iconImageView = view.findViewById(R.id.icon_image_view);
this.icon1ImageView = view.findViewById(R.id.icon_image_view1);
this.mRatingbar = view.findViewById(R.id.ratingBar);
this.likesTextView = view.findViewById(R.id.likes_counter_text_view);
}
}
}
主要是 Activity 与此相关,我有我的适配器
我有我的 Loader 覆盖方法
@Override
public Loader<List<Dish>> onCreateLoader(int i, Bundle bundle) {
Log.e(LOG_TAG, "Initializing OnCreate Loader");
if (dishList1.size() > 0) {
dishList1.clear();
dishAdapter.notifyDataSetChanged();
}
return new DishLoader(this, REQUEST_URL);
}
@Override
public void onLoadFinished(Loader<List<Dish>> loader, List<Dish> dishes) {
Log.e(LOG_TAG, "Initializing onFinished");
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
dishList1.clear();
Log.e(LOG_TAG, "Initializing onFinished Clear Adapter");
if (dishes != null && !dishes.isEmpty()) {
dishList1.clear();
dishList1 = dishes;
dishAdapter.setData(dishes);
}
}
请检查您的 php 脚本中的更新查询。
$query = "UPDATE tableName SET columnName = 'values', columnName = 'values' WHERE columnName = 'values';
$query = "UPDATE likes SET likes = '$likes'";
您忘记了 WHERE
子句。
我是 Android 的初学者,正在开发一个应用程序,该应用程序使用 PHP 脚本从 SQL 本地主机(临时)服务器获取数据以获得所需的 table并提取字段。现在按照教程一切都很好所以我有一个 ReyclerView
和 CustomAdapter
并且正在使用 LoaderManager
所以我有一个加载器也可以在我的 Utils Class
里面执行 fetchData 方法Class 有一些方法用于制作 HttpUrlConnection
直到从我的 SQL 数据库中提取 JSON 数据并将其提取到我的模型的 List<>
(Dish.Java) 其中包含导体和 getter 方法。
但现在我正在尝试将数据发送到另一个 table 例如用于项目喜欢或评级的每个项目为此目的我创建了新的 Table 它只包含喜欢作为 INT(后来附加到带有外键的项目),因此我搜索并找到了一个 PHP 脚本(适合我获取数据的白痴情况)如下:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
require 'connection.php';
updateLikes();
}
function updateLikes(){
global $connect;
$likes = $_POST['likes'];
$query = "UPDATE likes SET likes = '$likes'";
mysqli_query($connect,$query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
如果我尝试发出 POST
请求而不是 PUT,例如 Postman
我可以更改我的 table 中的喜欢字段。但不知道如何将其添加到我的查询中
因此,例如在评分后获取 Ratingbar
的值并将其累积到喜欢字段中的服务器(我知道这很荒谬)。
我发现我可以为 HttpUrlConnection
制作 setRequestMethod
到 "POST" 并像这样使用 DataOutputStream
:
class UpdateLikes extends AsyncTask<String, Void, Void> {
String URL = "http://localhost:81/likes.php";
@Override
protected Void doInBackground(String... params) {
String jsonData = params[0];
String charset = "UTF-8";
try {
java.net.URL url = new URL(URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
//send data
DataOutputStream os = new DataOutputStream(httpURLConnection.getOutputStream());
os.writeBytes(jsonData.toString());
//OutputStream dos = httpURLConnection.getOutputStream();
//dos.write(Integer.parseInt(jsonData.toString()));
//receive & read data response
InputStream is = httpURLConnection.getInputStream();
StringBuilder result = new StringBuilder();
int byteCharacter;
while ((byteCharacter = is.read()) != -1) {
result.append((char) byteCharacter);
}
Log.d("json api", "DoUpdateProduct.doInBackground Json return: " + result);
os.flush();
is.close();
os.close();
httpURLConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
这是我在 ratingbar 侦听器中执行 AsyncTask 的代码 doInBackground
String counter = String.valueOf(rating);
Like likes = new Like(counter);
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObject.put("likes",likes.likes);
jsonArray.put(jsonObject);
Log.d("json api", "Json array converted from Product: " + jsonArray.toString());
String jsonData = String.valueOf(jsonArray);
new UpdateLikes().execute(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e(MondayActivity.LOG_TAG, "Rating is:" + rating);
}
});
然后执行的事情是当我调试时我可以获得评级并将其设置到数组,建立连接但它不会更新我的数据库中的任何内容。
所以任何关于我如何实现这一点的建议,或者可能有完全另一种方法甚至重新考虑的方法,我都会感激不尽。
这是我的类所以你看看发生了什么
QuerUtils.Java
public class QueryUtils {
public static long date;
public static ArrayList<String> ls;
public QueryUtils() {
}
private static URL createUrl(String strUrl) {
URL url = null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
//TODO new
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
output.append(line);
line = bufferedReader.readLine();
}
}
return output.toString();
}
public static List<Dish> fetchData(String requestUrl) {
/* try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
URL url = createUrl(requestUrl);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Dish> dishes = extractFeatureFromJson(jsonResponse);
Log.i(LOG_TAG, "QueryUtils returns " + dishes);
return dishes;
}
private static List<Dish> extractFeatureFromJson(String jsonResponse) {
if (TextUtils.isEmpty(jsonResponse)) {
return null;
}
List<Dish> dishes = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
JSONObject jsonObject1 = null;
//dishes = new ArrayList<>();
ls = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject1 = (JSONObject) jsonArray.get(i);
if (jsonObject1 != null) {
String name = jsonObject1.getString("dish");
String daytime = jsonObject1.getString("daytime");
String dishName = jsonObject1.getString("dish");
String component = jsonObject1.getString("component");
double price = jsonObject1.getDouble("price");
String day = jsonObject1.getString("weakday");
int iconId_1 = jsonObject1.getInt("iconid_1");
int iconId_2 = jsonObject1.getInt("iconid_2");
date = jsonObject1.getLong("date");
int likesCounter = jsonObject1.getInt("likes");
String likes = String.valueOf((int) likesCounter);
Log.e(LOG_TAG, String.valueOf(date));
ls.add(jsonObject1.getString("date"));
Dish dish = new Dish(name, daytime, dishName,
component, price, day, date, iconId_1, iconId_2, likes);
dishes.add(dish);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return dishes;
}
}
DishAdapterTest.java
public class DishAdapterTest extends RecyclerView.Adapter<DishAdapterTest.ViewHolder> {
private List<Dish> dishes;
private Context context;
public DishAdapterTest(Context context, List<Dish> dishes) {
this.context = context;
this.dishes = dishes;
}
@NonNull
@Override
public DishAdapterTest.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item_dish, parent, false);
return new ViewHolder(itemView);
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
final Dish dish = dishes.get(position);
holder.daytimeTextView.setText(dish.getmDayTime());
holder.dishTextView.setText(dish.getmDish());
holder.componentTextView.setText(dish.getmComponent());
double originalPrice = dish.getmPrice();
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.GERMANY);
String price = format.format(originalPrice);
//String format2 = new DecimalFormat("#,###.00").format(dish.getmPrice());
holder.priceTextView.setText(price);
int icon_id = getIcon(dish.getmImageResId1());
holder.iconImageView.setImageResource(icon_id);
int icon_id2 = getIcon(dish.getmImageResId2());
holder.icon1ImageView.setImageResource(icon_id2);
holder.likesTextView.setText(dish.getmLikes());
holder.mRatingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Log.e(MondayActivity.LOG_TAG, "Rating is:" + rating);
}
});
}
public void setData(List<Dish> data) {
dishes.clear();
dishes.addAll(data);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
Log.i("DishAdapter Mensa ", "dishes.size() = " + dishes.size());
return dishes.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// The ViewHolder design pattern
private TextView daytimeTextView;
private TextView dishTextView;
private TextView componentTextView;
private TextView priceTextView;
private ImageView iconImageView;
private ImageView icon1ImageView;
private RatingBar mRatingbar;
private TextView likesTextView;
public ViewHolder(View view) {
super(view);
this.daytimeTextView = view.findViewById(R.id.daytime_text_view);
this.dishTextView = view.findViewById(R.id.dish_text_view);
this.componentTextView = view.findViewById(R.id.component_text_view);
this.priceTextView = view.findViewById(R.id.price_text_view);
this.iconImageView = view.findViewById(R.id.icon_image_view);
this.icon1ImageView = view.findViewById(R.id.icon_image_view1);
this.mRatingbar = view.findViewById(R.id.ratingBar);
this.likesTextView = view.findViewById(R.id.likes_counter_text_view);
}
}
}
主要是 Activity 与此相关,我有我的适配器 我有我的 Loader 覆盖方法
@Override
public Loader<List<Dish>> onCreateLoader(int i, Bundle bundle) {
Log.e(LOG_TAG, "Initializing OnCreate Loader");
if (dishList1.size() > 0) {
dishList1.clear();
dishAdapter.notifyDataSetChanged();
}
return new DishLoader(this, REQUEST_URL);
}
@Override
public void onLoadFinished(Loader<List<Dish>> loader, List<Dish> dishes) {
Log.e(LOG_TAG, "Initializing onFinished");
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
dishList1.clear();
Log.e(LOG_TAG, "Initializing onFinished Clear Adapter");
if (dishes != null && !dishes.isEmpty()) {
dishList1.clear();
dishList1 = dishes;
dishAdapter.setData(dishes);
}
}
请检查您的 php 脚本中的更新查询。
$query = "UPDATE tableName SET columnName = 'values', columnName = 'values' WHERE columnName = 'values';
$query = "UPDATE likes SET likes = '$likes'";
您忘记了 WHERE
子句。