簡単なユーザー登録フォームを作成しています。名前、パスワード、メールアドレスの3つのeditviewフィールドがあります。私のサーバーはRESTfulサーバーです。
私の問題は、POST変数(editviewのユーザー入力)をJSON形式で送信できないことです。私はこれに3日間取り組んでおり、stackoverflowやgoogleからほとんどすべてを試しました。助けてください
私のサーバーはこの形式のデータを受け入れます
"{\"fname\":\"xyz\",\"email\":\"xyz@yahoo.com\",\"password\":\"asd\"}"
私のサーバーはこの形式でそれを取得しているため、データベースエラーが発生し、JSON例外エラーが発生します。
email=xyz@yahoo.com&password=asd&fname=xyz
RegisterActivity.java
package com.login.recscores;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
EditText mUsername;
EditText mPassword;
EditText mEmail;
Button mSignUp ;
TextView temp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Edit Text
mUsername = (EditText)findViewById(R.id.name);
mEmail = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
temp=(TextView)findViewById(R.id.temp);;
// Create button
Button mSignUp = (Button) findViewById(R.id.sign_up_button);
// button click event
mSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewUser().execute();
}
});
}
/**
* Background Async Task to Create new user
* */
class CreateNewUser extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Signing Up..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
// Creating User
protected String doInBackground(String... args) {
String fname = mUsername.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
try {
String urlParameters = "fname="
+ URLEncoder.encode(fname, "UTF-8") + "&email="
+ URLEncoder.encode(email, "UTF-8")+ "&password="
+ URLEncoder.encode(password, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendPostData("http://10.0.2.2/api/register", urlParameters);
}
public static String sendPostData(String targetURL, String urlParameters) {
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
JSONパーサーは
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}