Created
July 16, 2014 12:48
-
-
Save johnsonyeap/2f365b1bf4c8c81413ce to your computer and use it in GitHub Desktop.
This is an example exercising GET Method and POST Method in Android by using HttpURLConnection class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mitgsl.johnsonyeap.androidassignment2; | |
import android.app.Activity; | |
import android.content.Context; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.Menu; | |
import android.view.MenuItem; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.io.Reader; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.util.ArrayList; | |
public class Survey extends Activity implements View.OnClickListener{ | |
private TextView question1, question2, question3; | |
private EditText answer1, answer2, answer3; | |
private ArrayList<String> answerArray = new ArrayList<String>(); | |
public JSONArray jArray; | |
private static final String SURVEY = "https://gsl-poll-app.herokuapp.com/surveys/1/"; | |
private static final String DEBUG_TAG = "HttpExample"; | |
private String dataSet; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.survey); | |
initialize(); | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
// Inflate the menu; this adds items to the action bar if it is present. | |
getMenuInflater().inflate(R.menu.survey, menu); | |
return true; | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
// Handle action bar item clicks here. The action bar will | |
// automatically handle clicks on the Home/Up button, so long | |
// as you specify a parent activity in AndroidManifest.xml. | |
int id = item.getItemId(); | |
return (id == R.id.action_settings) || super.onOptionsItemSelected(item); | |
} | |
@Override | |
public void onClick(View v) { | |
switch(v.getId()) { | |
case R.id.bSubmit: | |
new postData().execute(SURVEY); | |
Toast.makeText(getApplicationContext(), "Submitted successfully", Toast.LENGTH_LONG).show(); | |
break; | |
} | |
} | |
private void initialize() { | |
Button submit = (Button) findViewById(R.id.bSubmit); | |
question1 = (TextView) findViewById(R.id.tvQ1); | |
question2 = (TextView) findViewById(R.id.tvQ2); | |
question3 = (TextView) findViewById(R.id.tvQ3); | |
answer1 = (EditText) findViewById(R.id.etA1); | |
answer2 = (EditText) findViewById(R.id.etA2); | |
answer3 = (EditText) findViewById(R.id.etA3); | |
submit.setOnClickListener(this); | |
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); | |
if(networkInfo != null && networkInfo.isConnected()) | |
new getData().execute(SURVEY); | |
else | |
Toast.makeText(getApplicationContext(), "Unable to retrieve web page", Toast.LENGTH_LONG).show(); | |
} | |
private class getData extends AsyncTask<String, Void, String> { | |
String question; | |
int id; | |
@Override | |
protected String doInBackground(String... urls) { | |
try { | |
dataSet = downloadUrl(urls[0]); | |
} catch(IOException e) { | |
return "Unable to retrieve web page. URL may be invalid"; | |
} | |
return null; | |
} | |
@Override | |
protected void onPostExecute(String s) { | |
super.onPostExecute(s); | |
try { | |
jArray = new JSONArray(dataSet); | |
for(int x = 0; x < jArray.length(); x++) { | |
JSONObject jObject = jArray.getJSONObject(x); | |
id = jObject.getInt("id"); | |
question = jObject.getString("question_text"); | |
switch (id) { | |
case 1: | |
question1.setText(question); | |
break; | |
case 2: | |
question2.setText(question); | |
break; | |
case 3: | |
question3.setText(question); | |
break; | |
} | |
} | |
} catch (JSONException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} | |
//Fetches and processes the web page content and passes back a result string. | |
private String downloadUrl(String myurl) throws IOException { | |
String contentAsString; | |
InputStream is = null; | |
// Only display the first 500 characters of the retrieved | |
// web page content. | |
int len = 500; | |
try { | |
URL url = new URL(myurl); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setReadTimeout(10000 /* milliseconds */); | |
conn.setConnectTimeout(15000 /* milliseconds */); | |
conn.setRequestMethod("GET"); | |
conn.setDoInput(true); | |
// Starts the query | |
conn.connect(); | |
int response = conn.getResponseCode(); | |
Log.d(DEBUG_TAG, "The GET response is: " + response); | |
is = conn.getInputStream(); | |
// Convert the InputStream into a string | |
contentAsString = readIt(is, len); | |
return contentAsString; | |
// Makes sure that the InputStream is closed after the app is | |
// finished using it. | |
} finally { | |
if (is != null) { | |
is.close(); | |
} | |
} | |
} | |
// Reads an InputStream and converts it to a String. | |
public String readIt(InputStream stream, int len) throws IOException { | |
Reader reader; | |
reader = new InputStreamReader(stream, "UTF-8"); | |
char[] buffer = new char[len]; | |
reader.read(buffer); | |
return new String(buffer); | |
} | |
private class postData extends AsyncTask<String, Void, Void> { | |
@Override | |
protected Void doInBackground(String... urls) { | |
answerArray.add(answer1.getText().toString()); | |
answerArray.add(answer2.getText().toString()); | |
answerArray.add(answer3.getText().toString()); | |
HttpURLConnection c = null; | |
OutputStream os; | |
Integer question = 1; | |
JSONObject jResponse = new JSONObject(); | |
JSONObject jRespondent = new JSONObject(); | |
JSONArray jAnswers = new JSONArray(); | |
try { | |
jRespondent.put("first_name", "Johnson"); | |
jRespondent.put("last_name", "Yeap"); | |
for (String answer : answerArray) { | |
JSONObject jAnswer = new JSONObject(); | |
jAnswer.put("question", (question++).toString()); | |
jAnswer.put("response_text", answer); | |
jAnswers.put(jAnswer); | |
} | |
jRespondent.put("question_responses", jAnswers); | |
//passed | |
jResponse.put("response", jRespondent); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
byte[] data = jResponse.toString().getBytes(); | |
try { | |
URL url = new URL(urls[0]); | |
c = (HttpURLConnection) url.openConnection(); | |
c.setDoOutput(true); | |
c.setFixedLengthStreamingMode(data.length); | |
c.connect(); | |
os = c.getOutputStream(); | |
if (os != null) { | |
os.write(data); | |
os.close(); | |
} | |
int responseCode = c.getResponseCode(); | |
Log.d(DEBUG_TAG, "POST Response Code = " + responseCode); | |
InputStream is = c.getInputStream(); | |
String result = readIt(is, 1000); | |
Log.d(DEBUG_TAG, "Response = " + result); | |
responseCode = c.getResponseCode(); | |
Log.d(DEBUG_TAG, "GET Response Code = " + responseCode); | |
} catch (MalformedURLException e) { | |
//If the URL is not a valid URL. | |
e.printStackTrace(); | |
} catch (IOException e) { | |
//If an error prevented opening or writing to the stream. | |
e.printStackTrace(); | |
} | |
finally { | |
//This clause ensures that disconnect() is always run last, | |
//even after an exception is caught. You should wrap | |
//reader.readLine() like this too. | |
if (c != null) | |
c.disconnect(); | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment