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
| public class ReponseTestActivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
String rep;
public static URL url;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
try {
url = new URL("http://mon@ip/android/lecture.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rep = postURL(url, "test");
txt.setText(rep);
txt.setText(rep);
}
public static String postURL(URL a_Url, String a_sParamsToPost)
{
StringBuilder Sb = new StringBuilder();
//recup du saut de ligne
String sLineSep = null;
try
{
sLineSep = System.getProperty("line.separator");
}
catch (Exception e)
{
sLineSep = "\n\r";
}
try
{
HttpURLConnection UrlConn = (HttpURLConnection) a_Url.openConnection();
UrlConn.setRequestMethod("POST");
UrlConn.setAllowUserInteraction(false);
//envoyer des params
UrlConn.setDoOutput(true);
//poster les params
PrintWriter ParamWriter = new PrintWriter(UrlConn.getOutputStream());
ParamWriter.print(a_sParamsToPost);
//fermer le post avant de lire le resultat ... logique
ParamWriter.flush();
ParamWriter.close();
//Lire la reponse
InputStream Response = UrlConn.getInputStream();
BufferedReader BufReader = new BufferedReader(new InputStreamReader(Response));
String sLine;
while ((sLine = BufReader.readLine()) != null)
{
Sb.append(sLine+"\n\r");
Sb.append(sLineSep);
//System.out.println(Sb);
}
//deconnection
UrlConn.disconnect();
}
catch(ConnectException ctx)
{
//Log.fatal(this, "Connection lost : server may be down");
ctx.printStackTrace();
}
catch (Exception e)
{
//Log.error(this,"postURL : "+e.getMessage());
e.printStackTrace();
}
//Log.debug(this, "retour url="+o_oSb.toString());
return Sb.toString();
}
} |
Partager