老罗视频学习笔记。
一.客户端。
和上一篇java提供的接口传递数据基本类似。
sendHttpClientPost函数如下:
private static String sendHttpClientPost(String path,Map<String, String> params,String encode){
//进行一下封装
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
if(params!=null && !params.isEmpty()){
for(Entry<String, String> entry : params.entrySet()){
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
//实现将请求的参数封装到表单中,请求提交
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode);
//使用post方式进行提交
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
//指定post请求
DefaultHttpClient client = new DefaultHttpClient();
//返回请求结果
HttpResponse httpResponse = client.execute(httpPost);
//判断请求结果
if(httpResponse.getStatusLine().getStatusCode() == 200){
return ChangeInputStream(httpResponse.getEntity().getContent(),encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encode;
}
ChangeInputStream函数如下:和上一篇一样
private static String ChangeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String resultString = "";
if(inputStream!=null) {
try {
//数据循环存储在outputStream中
while ((len=inputStream.read(data))!=-1) {
outputStream.write(data,0,len);
}
//首先转换为字节数组,然后以encode编码格式转换为字符串
resultString = new String(outputStream.toByteArray(),encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
测试代码如下:
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "123");
String encode = "utf-8";
String resString = httpUrils.sendHttpClientPost(path, params, encode);
System.out.print("------>"+resString);
}
二.服务器端
和上一篇的一样,这几篇http协议都用同一个服务器就可以