我正在构建一个用户登录的Android应用程序,并输入Name,MailId和Birthday等基本信息。
我想在我的服务器中解析所有这些数据我创建了一个API链接,它将保存服务器数据库中的所有用户信息。
现在的问题是如何将此用户信息发送到该API链接。
这是我的代码 -
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputprofilepic;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_PROFILEPIC = "profilepic";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
//inputFullName = (EditText) findViewById(R.id.registerName);
//inputEmail = (EditText) findViewById(R.id.registerEmail);
//inputprofilepic = (EditText) findViewById(R.id.registerPassword);
//btnRegister = (Button) findViewById(R.id.btnRegister);
//btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
//registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
//btnRegister.setOnClickListener(new View.OnClickListener() {
//public void onClick(View view) {
String name = "hey";
String email = "bbye";
String profilepic = "thanks!";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, profilepic);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
//registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
json.getString(KEY_PROFILEPIC));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(),
DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
//registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//}
//});
// Link to Login Screen
//btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
//public void onClick(View view) {
// Close Registration View
//finish();
//}
//});
}
}
这是我的json代码 -
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
这是我的用户功能代码 -
public class UserFunctions {
private JSONParser jsonParser;
private static String registerURL = "http://url";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String profilepic){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("profilepic", profilepic));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String profilepic){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("profilepic", profilepic));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
答案 0 :(得分:1)
public String postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", myNameString));
nameValuePairs.add(new BasicNameValuePair("password", myPasswordString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream parse = entity.getContent();
return getStringFromInputStream(parse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return "No Result !";
}
//convert InputStream to String
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
答案 1 :(得分:0)
尝试使用url来发送数据而不是json解析。
url1 =&#34; http://&#34; + ip +&#34; /service.svc/AndPOMasterAdd?Auto =&#34; +自动+&#34;&amp; ClientId =&#34; + ClientId +&#34;&amp; FinYr =&#34; + FinYr +&#34;&amp; PDate =&#34; + PDate +&# 34;&amp; PTime =&#34; + PTime +&#34;&amp; SuppID =&#34; + SuppID +&#34;&amp; City =&#34; + City +&#34;&amp; Prodid =&#34; + Prodid +&#34;&amp; Design =&#34; + Design +&#34;&amp; Qty =&#34; + Qty +&#34;&amp; Rate =&#34; + Rate +&#34;&amp; ImgPName =&#34; + ImageName +&#34;&amp; CrBy =&#34; + CRBY +&#34;&amp; CrDate =&#34; + CRdate +&# 34;&amp;备注=&#34; +备注+&#34;&amp; ForBranch =&#34; + ForBranch +&#34;&#34 ;;