package
com.lifengfeng.submitdata.utils;
import
java.io.ByteArrayOutputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.OutputStream;
import
java.net.HttpURLConnection;
import
java.net.MalformedURLException;
import
java.net.URL;
import
java.net.URLConnection;
import
java.net.URLEncoder;
import
android.util.Log;
public
class
NetUtils {
private
static
final
String TAG =
"NetUtils"
;
/**
* 使用post的方式登录
* @param userName
* @param password
* @return
*/
public
static
String loginOfPost(String userName, String password) {
HttpURLConnection conn =
null
;
try
{
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(
"POST"
);
conn.setConnectTimeout(
10000
);
conn.setReadTimeout(
5000
);
conn.setDoOutput(
true
);
String data =
"username="
+ userName +
"&password="
+ password;
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int
responseCode = conn.getResponseCode();
if
(responseCode ==
200
) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
return
state;
}
else
{
Log.i(TAG,
"访问失败: "
+ responseCode);
}
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
if
(conn !=
null
) {
conn.disconnect();
}
}
return
null
;
}
/**
* 使用get的方式登录
* @param userName
* @param password
* @return 登录的状态
*/
public
static
String loginOfGet(String userName, String password) {
HttpURLConnection conn =
null
;
try
{
String data =
"username="
+ URLEncoder.encode(userName) +
"&password="
+ URLEncoder.encode(password);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(
"GET"
);
conn.setConnectTimeout(
10000
);
conn.setReadTimeout(
5000
);
int
responseCode = conn.getResponseCode();
if
(responseCode ==
200
) {
InputStream is = conn.getInputStream();
String state = getStringFromInputStream(is);
return
state;
}
else
{
Log.i(TAG,
"访问失败: "
+ responseCode);
}
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
if
(conn !=
null
) {
conn.disconnect();
}
}
return
null
;
}
/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private
static
String getStringFromInputStream(InputStream is)
throws
IOException {
ByteArrayOutputStream baos =
new
ByteArrayOutputStream();
byte
[] buffer =
new
byte
[
1024
];
int
len = -
1
;
while
((len = is.read(buffer)) != -
1
) {
baos.write(buffer,
0
, len);
}
is.close();
String html = baos.toString();
baos.close();
return
html;
}
}