카톡
◎위챗 : speedseoul
you want to send JSON data from Android app to a server, how do you go about doing it. Follow the steps below to use Async thread to do it.
In the Android Manifest file add following permissions,
--------------- <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> The App Layout & Views ----------------------- Main layout is LinearLayout Three EditTextViews “FirstName, LastName & Age” One Button to send “post” data to the server. On button add attribute onclick and corresponds to the java function that is in current Activity The App Layout for main_activity.xml <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="16dp" android:layout_marginTop="16dp" android:layout_marginRight="16dp" android:layout_marginBottom="30dp" android:orientation="vertical"> <EditText android:layout_width="fill_parent" android:id="@+id/FirstName" android:layout_height="40dp" android:hint="First Name" android:background="#f3f3f3" android:paddingLeft="5dp" android:layout_marginTop="30dp"/> <EditText android:layout_width="fill_parent" android:id="@+id/LastName" android:layout_height="40dp" android:hint="Last Name" android:background="#f3f3f3" android:paddingLeft="5dp" android:layout_marginTop="15dp"/> <EditText android:layout_width="fill_parent" android:id="@+id/Age" android:layout_height="40dp" android:hint="Age" android:background="#f3f3f3" android:paddingLeft="5dp" android:layout_marginTop="15dp" android:inputType="number"/> <Button android:layout_width="190dp" android:layout_height="50dp" android:layout_gravity="center_horizontal" android:layout_marginTop="16dp" android:text="Submit" android:textSize="20sp" android:id="@+id/userinfo" android:onClick="senddatatoserver"/> </LinearLayout>,
Activity
In the activity, create method to do the following:
public class DashboardActivity extends Activity { EditText AgeView;
EditText LastNameView;
EditText FirstNameView;
String FirstName;
String LastName;
String Age;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get reference to the defined views in layout file FirstNameView = (EditText) findViewById(R.id.FirstName);
LastNameView = (EditText) findViewById(R.id.LastName);
AgeView = (EditText) findViewById(R.id.Age);
}
public void senddatatoserver(View v) {
//function in the activity that corresponds to the layout button
FirstName = FirstNameView.getText().toString();
LastName = LastNameView.getText().toString();
Age = AgeView.getText().toString();
JSONObject post_dict = new JSONObject();
try {
post_dict.put("firstname" , FirstName);
post_dict.put("firstname", LastName);
post_dict.put("firstname", Age);
} catch (JSONException e) {
e.printStackTrace();
}
if (post_dict.length() > 0) {
new SendJsonDataToServer().execute(String.valueOf(post_dict));
#call to async class
}
//add background inline class here
class SendJsonDataToServer extends Async<String,String,String>{
}}
Async Background Task
Helps in creating the connection in a separate thread so the UI will not freeze.
Do following steps to implement it:
class SendDataToServer extends AsyncTask <String,String,String>{
@Override
protected String doInBackground(String... params) {
}
@Override
protected void onPostExecute(String s) {
}
}
}Network call
In the doInBackground do following things.
@Override
protected String doInBackground(String... params) {
String JsonResponse = null;
String JsonDATA = params[0]; HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://appliedinformatics.com/trialx");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
//response data
Log.i(TAG,JsonResponse);
try {
//send to post execute
return JsonResponse;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
return null;
}We will be posting more blogs on Android. Stay tuned!