Android HttpURLConnection
2054 ワード
GoogleのオススメはHttpUrlConnectionです.
HttpURLConnectionはデフォルトでGET方式を使用します.
HttpURLConnectionはデフォルトでGET方式を使用します.
URL url = new URL("www.baidu.com");
// HttpURLConnection
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// ( )
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
// BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
//
while (((inputLine = buffer.readLine()) != null)){
// "
"
resultData += inputLine + "
";
}
// InputStreamReader
in.close();
// http
urlConn.disconnect();
POST方式を使うなら、set Request Method設定が必要です.String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//
String resultData = "";
URL url = null;
try {
// URL
url = new URL(httpUrl);
}
catch (MalformedURLException e){
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null){
try{
// HttpURLConnection
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// post , true
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// POST
urlConn.setRequestMethod("POST");
// Post
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
// Content-type, application/x-www-form-urlencoded
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// , postUrl.openConnection() connect ,
// connection.getOutputStream connect。
urlConn.connect();
//DataOutputStream
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
//
String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
//
out.writeBytes(content);
// 、
out.flush();
out.close();
//
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getinputstream()))
string line = br.readline();
while(line != null){
system.out.printli(line);
line = br.readline();
}