我正在创建一个将数据存储在数据库中的应用程序,然后检索它。 在服务器端,我正在使用PHP,在客户端,我有这个文件获取输入并将其传递给PHP文件。
new AsyncTask<String, String, String>() {
JSONParser jsonParser = new JSONParser();
private ProgressBar pBar;
private String url_post_pet = "http://192.168.0.13/Android/post_pet.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
//pBar = new ProgressBar();
//pBar.setIndeterminate(false);
//pBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... args) {
// Building Parameters
HashMap<String, String> params = new HashMap<>();
params.put("name", a);
params.put("breed", BREED);
params.put("type", TYPE);
params.put("images", "Whatever");
params.put("description", c);
params.put("coords", b);
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_post_pet,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
System.out.println("exception" + e);
e.printStackTrace();
}
System.out.println("nul");
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
//pBar.dismiss();
}
}.execute();
}
});
}
另外,我有这个JSONParser:
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
System.out.println(jObj);
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
这是我每次提交数据时都会遇到的错误:
08-26 12:51:08.236 5089-5156 / chtecnologies.myapplication D / JSON解析器:结果:08-26 12:51:08.239 5089-5156 / chtecnologies.myapplication E / JSON解析器:解析数据组织时出错。 json.JSONException:字符0的输入结束 08-26 12:51:08.793 5089-5096 / chtecnologies.myapplication W / art:暂停所有线程:190.496ms 08-26 12:51:09.245 5089-5096 / chtecnologies.myapplication W / art:暂停所有线程:137.277ms 08-26 12:51:09.267 5089-5156 / chtecnologies.myapplication E / AndroidRuntime:致命异常:AsyncTask#1 过程:chtecnologies.myapplication,PID:5089 java.lang.RuntimeException:执行doInBackground()时发生错误 在android.os.AsyncTask $ 3.done(AsyncTask.java:304) 在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 在java.util.concurrent.FutureTask.run(FutureTask.java:242) 在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587) 在java.lang.Thread.run(Thread.java:818) 引发者:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.String org.json.JSONObject.toString()' 在chtecnologies.myapplication.PostPet $ 4 $ 1.doInBackground(PostPet.java:154) 在chtecnologies.myapplication.PostPet $ 4 $ 1.doInBackground(PostPet.java:118) 在android.os.AsyncTask $ 2.call(AsyncTask.java:292) 在java.util.concurrent.FutureTask.run(FutureTask.java:237) 在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587) 在java.lang.Thread.run(Thread.java:818)
数据成功进入数据库,但JSONParser中似乎存在问题,而无法获取PHP文件的结果。
您是否会告诉我JSONParser文件或其他地方是否有任何错误?这是我第一次在我的应用程序中实现服务器,希望你能帮助我!谢谢
答案 0 :(得分:1)
您发送数据的方式看起来很可疑。如果您想在POST中发送数据,请使用HttpURLConnection
,如
String postParam = "name=" + a + "&breed=" + BREED + "&type=" + "&images=" +
Whatever + "&description=" + c + "&coords=" + b;
try{
URL url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStream os = connection.getOutputStream();
os.write(postParam.getBytes());
os.flush();
os.close();
// Fetching the response code
responseCode = connection.getResponseCode();
Log.d(TAG, "POST Response Code: " + responseCode);
} catch(Exception e) {
e.printStackTrace();
}
connection.setRequestMethod - 设置您希望使用GET / POST发送数据的方法
connection.setDoOutput(true) - 让您发送输出
connection.setDoInput(true) - 让您在发送数据后接收输入(如果有的话)
希望这能解决您的问题!