以前,我可以远程访问php中的字符串。我一开始觉得很难,但AsyncTask为我做了工作。现在,我可以访问从php到sql server的查询结果。但我想从我的java类传递一个字符串到php,当我搜索一些信息时,我看到了一些JSON帖子并获取代码,但我无法清楚地理解它们。这是我的代码:
protected String doInBackground(Void... params) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
该字符串包含在“sb.toString()”中。现在我如何在我的代码中添加一个JSON来将字符串从java发送到php,并且还从php获取结果字符串到java。提前感谢您的帮助。
答案 0 :(得分:0)
如果从服务器收到JSON格式的响应,请首先将json字符串设为JSONObject。然后阅读json数据供您使用。
try {
JSONObject obj = new JSONObject(sb.toString()); // make string to json obj
Iterator iter = obj.keys(); // get all keys from json obj and iterating
while(iter.hasNext()){
String key = (String)iter.next();
String str = obj.get(key).toString();
// write your code
}
} catch(Exception e) {
e.printStackTrace();
}
您的代码已包含您问题的答案。在创建url连接之后,只需添加用于使用OutputStreamWriter将数据发送到服务器的参数,就像使用InpustStreamReader接收响应一样。
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
// wrtie params
OutputStreamWriter we = new OutputStreamWriter(urlConnection.getOutPutStream());
wr.write(data); // data (make json obj to 'key=value' string)
wr.flush();
wr.close();
// read response
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}enter code here