作者:sdfaghasfdg4 | 来源:互联网 | 2023-05-17 01:49
在工作线程中进行此操作:
GET请求:
public String loginOfGet(String username, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
String uri = "http://xxx?";
String data = "username=" + username + "&password=" + password;
HttpGet get = new HttpGet(uri + data);
HttpResponse respOnse= client.execute(get);
int stateCode = response.getStatusLine().getStatusCode();
if (200 == stateCode) {
InputStream is = response.getEntity().getContent();
String result = getStringFromInputStream(is);
return result;
} else {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null){
client.getConnectionManager().shutdown();
}
}
return null;
}
POST请求:
public String loginOfPost(String username, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
String uri = "http://xxx?";
HttpPost post = new HttpPost(uri);
List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
post.setEntity(entity);
HttpResponse respOnse= client.execute(post);
int stateCode = response.getStatusLine().getStatusCode();
if (200 == stateCode) {
InputStream is = response.getEntity().getContent();
String result = getStringFromInputStream(is);
return result;
} else {
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(client != null){
client.getConnectionManager().shutdown();
}
}
return null;
}
/**
* 根据流返回一个字符串信息
*/
private String getStringFromInputStream(InputStream is) throws Exception {
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;
}