1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener {
// private static final String CLASSTAG = SimpleGet.class.getSimpleName();
private EditText getInput;
private TextView getOutput;
private Button getButton;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
this.getInput = (EditText) findViewById(R.id.get_input);
getInput.setText("http://10.0.2.2:8888/index.php");
this.getOutput = (TextView) findViewById(R.id.get_output);
this.getButton = (Button) findViewById(R.id.get_button);
this.getButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
getOutput.setText("");
String output = getHttpResponse(getInput.getText().toString());
if (output != null) {
getOutput.setText(output);
}
}
});
};
/**
* Perform an HTTP GET with HttpUrlConnection.
*
* @param location
* @return
*/
private String getHttpResponse(String location) {
StringBuffer result = new StringBuffer();
URL url = null;
// Log.d(Constants.LOGTAG, " " + SimpleGet.CLASSTAG + " location = " + location);
try {
url = new URL(location);
// Log.d(Constants.LOGTAG, " " + SimpleGet.CLASSTAG + " url = " + url);
} catch (MalformedURLException e) {
// Log.e(Constants.LOGTAG, " " + SimpleGet.CLASSTAG + " " + e.getMessage());
}
if (url != null) {
try {
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine;
int lineCount = 0; // limit the lines for the example
while ((lineCount < 10) && ((inputLine = in.readLine()) != null)) {
lineCount++;
// Log.v(Constants.LOGTAG, " " + SimpleGet.CLASSTAG + " inputLine = " + inputLine);
result.append(inputLine);
//result += "\n" + inputLine;
}
in.close();
urlConn.disconnect();
} catch (IOException e) {
// Log.e(Constants.LOGTAG, " " + SimpleGet.CLASSTAG + " " + e.getMessage());
}
} else {
// Log.e(Constants.LOGTAG, " " + SimpleGet.CLASSTAG + " url NULL");
}
return result.toString();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
} |