i am following a tutorial on androidhive, but i am not able to pass post parameters, their are certain solutions but none worked for me.
我正在关注androidhive的教程,但我无法传递帖子参数,他们是某些解决方案,但没有一个对我有用。
PHP CODE:
require("config.inc.php");
$organizationname = $_POST['organizationname'];
$date = $_POST["dates"];
//$date = "19-08-2015";
//$organizationname = "xyz123";
//initial query
$query2 = "SELECT rollno,studentname,`$date` FROM `attendencee` WHERE organizationname = '$organizationname' ";
As you can see there are commented variables, when i use them the code works fine, but when i try to use the values received, the error shows variables not defined.
正如您所看到的那样,有注释变量,当我使用它们时代码工作正常,但是当我尝试使用接收到的值时,错误显示未定义的变量。
CODE:
public class JsonRequestActivity extends Activity implements OnClickListener {
private String TAG = JsonRequestActivity.class.getSimpleName();
private Button btnJsonObj, btnJsonArray;
private TextView msgResponse;
private ProgressDialog pDialog;
// These tags will be used to cancel the requests
private String tag_json_obj = "jobj_req", tag_json_arry = "jarray_req";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
btnJsonObj = (Button) findViewById(R.id.btnJsonObj);
btnJsonArray = (Button) findViewById(R.id.btnJsonArray);
msgResponse = (TextView) findViewById(R.id.msgResponse);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
btnJsonObj.setOnClickListener(this);
btnJsonArray.setOnClickListener(this);
}
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}
/**
* Making json object request
* */
private void makeJsonObjReq() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Const.URL_JSON_OBJECT, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("dates", "19-08-2015");
params.put("organizationname", "xyx123");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
/**
* Making json array request
* */
private void makeJsonArryReq() {
showProgressDialog();
JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
msgResponse.setText("Error: " + error.getMessage());
hideProgressDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req,
tag_json_arry);
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnJsonObj:
makeJsonObjReq();
break;
case R.id.btnJsonArray:
makeJsonArryReq();
break;
}
}
}
3 个解决方案
#1
0
1) Http method must be POST not Method.GET 2) Change:
1)Http方法必须是POST而不是Method.GET 2)更改:
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("dates", "19-08-2015");
params.put("organizationname", "xyx123");
return params;
}
to:
@Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
body = mJson.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Logcat.e(TAG, "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
mJson
is your JSON
(String)
mJson是你的JSON(String)
#2
0
I had the same problem. "getParams" won't work. Suppose you want to post a user object to server, First you create a user json object then you post it like this:
我有同样的问题。 “getParams”不起作用。假设您要将用户对象发布到服务器,首先您创建一个用户json对象,然后将其发布如下:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("Email", email);
jsonBody.put("Username", name1);
jsonBody.put("Password", password);
jsonBody.put("ConfirmPassword", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest strReq = new JsonObjectRequest(Request.Method.POST,
AppConfig.URL_REGISTER, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jObj) {
// do these if it request was successful
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// do these if it request has errors
}
}) {
@Override
public String getBodyContentType() {
return "application/json";
}
};
#3
0
If your issue has not been fixed, try my following code:
如果您的问题尚未解决,请尝试以下代码:
Map<String, String> stringMap = new HashMap<>();
stringMap.put("key1", "value1");
stringMap.put("key2", "value2");
final String requestBody = buildRequestBody(stringMap);
...
public String buildRequestBody(Object content) {
String output = null;
if ((content instanceof String) ||
(content instanceof JSONObject) ||
(content instanceof JSONArray)) {
output = content.toString();
} else if (content instanceof Map) {
Uri.Builder builder = new Uri.Builder();
HashMap hashMap = (HashMap) content;
if (hashMap != null) {
Iterator entries = hashMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove(); // avoids a ConcurrentModificationException
}
output = builder.build().getEncodedQuery();
}
}
return output;
}
Inside your POST Request, override 2 following methods:
在POST请求中,覆盖以下两种方法:
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
#1
0
1) Http method must be POST not Method.GET 2) Change:
1)Http方法必须是POST而不是Method.GET 2)更改:
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("dates", "19-08-2015");
params.put("organizationname", "xyx123");
return params;
}
to:
@Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
body = mJson.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Logcat.e(TAG, "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
mJson
is your JSON
(String)
mJson是你的JSON(String)
#2
0
I had the same problem. "getParams" won't work. Suppose you want to post a user object to server, First you create a user json object then you post it like this:
我有同样的问题。 “getParams”不起作用。假设您要将用户对象发布到服务器,首先您创建一个用户json对象,然后将其发布如下:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("Email", email);
jsonBody.put("Username", name1);
jsonBody.put("Password", password);
jsonBody.put("ConfirmPassword", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest strReq = new JsonObjectRequest(Request.Method.POST,
AppConfig.URL_REGISTER, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jObj) {
// do these if it request was successful
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// do these if it request has errors
}
}) {
@Override
public String getBodyContentType() {
return "application/json";
}
};
#3
0
If your issue has not been fixed, try my following code:
如果您的问题尚未解决,请尝试以下代码:
Map<String, String> stringMap = new HashMap<>();
stringMap.put("key1", "value1");
stringMap.put("key2", "value2");
final String requestBody = buildRequestBody(stringMap);
...
public String buildRequestBody(Object content) {
String output = null;
if ((content instanceof String) ||
(content instanceof JSONObject) ||
(content instanceof JSONArray)) {
output = content.toString();
} else if (content instanceof Map) {
Uri.Builder builder = new Uri.Builder();
HashMap hashMap = (HashMap) content;
if (hashMap != null) {
Iterator entries = hashMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove(); // avoids a ConcurrentModificationException
}
output = builder.build().getEncodedQuery();
}
}
return output;
}
Inside your POST Request, override 2 following methods:
在POST请求中,覆盖以下两种方法:
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}