从服务器接收响应时出错?
Posted
技术标签:
【中文标题】从服务器接收响应时出错?【英文标题】:Error receiving response from the server? 【发布时间】:2018-02-04 11:01:01 【问题描述】:我正在制作一个将一些数据存储在数据库中的应用程序,然后它会检索它。 在服务器端我使用 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/艺术:暂停所有线程占用:190.496ms 08-26 12:51:09.245 5089-5096/chtecnologies.myapplication W/艺术:暂停所有线程占用: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) 在 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) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 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) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 在 java.lang.Thread.run(Thread.java:818)
数据成功进入数据库,但JSONParser似乎有问题,无法得到PHP文件的结果。
如果 JSONParser 文件或其他地方有什么问题,您能告诉我吗?这是我第一次在我的应用程序中实现服务器,希望你能帮助我!谢谢
【问题讨论】:
【参考方案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)- 让您在发送数据后接收输入(如果有)
希望这能解决您的问题!
【讨论】:
以上是关于从服务器接收响应时出错?的主要内容,如果未能解决你的问题,请参考以下文章
使用 Jetty 9 从 HttpClient 获取响应时出错