Android examples for Network:HTTP Request
request By HTTP Post via URL
//package com.java2s; import java.io.DataOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import android.util.Log; public class Main { private static final int HTTP_200 = 200; private static final String TAG_POST = "Web POST"; public static void requestByPost(String path) throws Throwable { // byte/*from w w w . java 2s.co m*/ String params = "id=" + URLEncoder.encode("t_stop", "UTF-8"); byte[] postData = params.getBytes(); // ?URL URL url = new URL(path); // HttpURLConnection HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); // urlConn.setConnectTimeout(5 * 10000); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod("POST"); urlConn.setInstanceFollowRedirects(true); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // urlConn.connect(); // DataOutputStream dos = new DataOutputStream( urlConn.getOutputStream()); dos.write(postData); dos.flush(); dos.close(); // if (urlConn.getResponseCode() == HTTP_200) { // byte[] data = readStream(urlConn.getInputStream()); } } public static byte[] readStream(InputStream inStream) throws Exception { int count = 0; while (count == 0) { count = inStream.available(); } byte[] b = new byte[count]; inStream.read(b); return b; } }