我想对具有某些参数(名称,电子邮件,密码等)的用户注册进行简单的HTTPRequest到php脚本。我已经尝试了许多来自Internet的教程,但对我没有任何帮助。 HTTP POST抛出NullpointerException
。在后端也显示null。
我的代码是:
//JSON Node Names
private static final String TAG_ID = "status";
private static final String TAG_NAME = "code";
private static final String TAG_EMAIL = "message";
//POST data
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("user_name", "Steve"));
nameValuePairs.add(new BasicNameValuePair("user_email", "jjdnjdn"));
nameValuePairs.add(new BasicNameValuePair("user_password", "dcds"));
nameValuePairs.add(new BasicNameValuePair("user_phone_number", "2343"));
nameValuePairs.add(new BasicNameValuePair("club_member_id", "24"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//For receiving response
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.e("Data", String.valueOf(json));
try {
String id = json.getString(TAG_ID);
String name = json.getString(TAG_NAME);
String email = json.getString(TAG_EMAIL);
Toast.makeText(getContext(), id , Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), name , Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(), email , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
Logcat错误
E/JSON Parser: Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
E/Data: null
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
PHP代码
<?php
print_r($_POST);
?>
获取空数组。
最佳答案
jParser.getJSONFromUrl(url)似乎是GET而不是POST(而且无论如何您都没有使用httppost或从jParser引用了它,因此它不能确定是否发布数据。
在ephp中,您可能还需要在回显json主体之前发送正确的Content-type标头,因为jParser可能依赖于它。