写SudaLogin Android app时,找了Java方面的网络编程方法。
HttpURLConnection作为Android官方文档中建议的网络编程库,稳定可靠,现整理如下:
HttpURLConnection -
Java网络编程
1 POST报文
1.1 依赖包
1 2 3 4 5 6
| import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder;
|
1.2 编程示例
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
| try { String spec = "http://example.com/example"; URL url = new URL(spec); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000);
String data = "-->POST报文数据!<--" System.out.println(data);
urlConnection.setDoOutput(true); urlConnection.setDoInput(true); OutputStream os = urlConnection.getOutputStream(); os.write(data.getBytes()); os.flush();
InputStream is = urlConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte buffer[] = new byte[1024]; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } final String result = baos.toString();
is.close(); baos.close();
} catch (Exception e) { e.printStackTrace(); }
|