老罗视频学习笔记。
一.客户端。
和上一篇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协议都用同一个服务器就可以
这篇博客是老罗视频学习笔记,详细介绍了如何使用Apache接口通过POST方式传递数据。在客户端,函数sendHttpClientPost和ChangeInputStream的实现与之前Java接口传递数据相似。测试代码也进行了展示。在服务器端,同样沿用之前的HTTP协议处理方式。

5965

被折叠的 条评论
为什么被折叠?



