package com.smart.net.utils;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class NetTool {
/**
* byte[] data=param.getBytes(); 以后要注意,发送数据接收数据,都要用字节数组去接收它
*
*
* Content-Type 指action entype="multipart/x-"
* */
public static InputStream sendPostRequest(String uriPath,
Map<String, String> params, String encoding) throws Exception {
// String param="id=67&name"+URLEncoder.encode("老梁","UTF-8");//要发送的数据
StringBuilder sb = new StringBuilder();
// 进行封装
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append('&');
}
sb.deleteCharAt(sb.length() - 1);
byte[] data = sb.toString().getBytes();
URL url = new URL(uriPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000);
conn.setDoOutput(true);// 发送POST至服务器
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream dataOutStream = new DataOutputStream(
conn.getOutputStream());// 得到输出流
dataOutStream.write(data);
dataOutStream.flush();
dataOutStream.close();
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() == 200) {
return conn.getInputStream();
}
return null;
}
/**
*
*
* */
public static String getTextContent(InputStream inStream,String encoding) throws Exception {
byte[] data=readStream(inStream);
return new String(data,encoding);
}
/**
* 获取URL路径指定的内容
*
*
* 获得指定内容
* */
public static String getTextContent2(String path,String encoding) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6 * 1000);
// 别超过10秒。
System.out.println(conn.getResponseCode());
if(conn.getResponseCode()==200){
InputStream inputStream=conn.getInputStream();
byte[] data=readStream(inputStream);
return new String(data,encoding);
}
return null;
}
/**
* 直接可以得到文本与流的数据
* */
public static InputStream getContent(String uriPath) throws Exception {
URL url = new URL(uriPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6 * 1000);
// 别超过10秒。
System.out.println(conn.getResponseCode());
if(conn.getResponseCode()==200){
return conn.getInputStream();
}
return null;
}
// /**
// * 直接可以得到文本与流的数据
// * */
public static InputStream getContentImputStream(String path,String encoding) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6 * 1000);
// 别超过10秒。
System.out.println(conn.getResponseCode());
if(conn.getResponseCode()==200){
return conn.getInputStream();
}
return null;
}
/**
* 获取指定路径,的数据。
*
* **/
public static byte[] getImage(String urlpath) throws Exception {
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6 * 1000);
// 别超过10秒。
if(conn.getResponseCode()==200){
InputStream inputStream=conn.getInputStream();
return readStream(inputStream);
}
return null;
}
/**
* 读取数据
* 输入流
*
* */
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outstream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=-1;
while((len=inStream.read(buffer)) !=-1){
outstream.write(buffer, 0, len);
}
outstream.close();
inStream.close();
return outstream.toByteArray();
}
}
package com.smart.activity;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.test.AndroidTestCase;
import android.util.Log;
import com.smart.net.utils.FormFile;
import com.smart.net.utils.HttpRequester;
import com.smart.net.utils.NetTool;
/**
* 如何使用大数据发送
* */
public class PostParamTest extends AndroidTestCase {
/***
* 本代码报错,原因为数据类型不对,18 向Internet上传文件-1.avi 38:38分
*
*
* */
private final String TAG = "PostParamTest";
/***
* 上专文件,
* 要有四部份数据
* 名称
* 内容类型
* 表单字段名称
* 类型
* 发送文件及文本请求参数
*
* 面试上专100M
* 文件读成数组,然后写上传上去
*上传到网络流里面去,
* */
//发送文件及文本请求参数
public void testSendPostFileparams() throws Exception{
Map<String,String> params=new HashMap<String,String>();
params.put("method", "save");
params.put("id", "988");
params.put("name", "老梁");
FileInputStream inStream=new FileInputStream(new File("/sdcard/smart.xml"));
// byte[] data=NetTool.readStream(inStream);
// inStream.close();
FormFile file=new FormFile("smart.xml",inStream,"file","test/xml");
//这行代码出现报错
// HttpRequester.post("www.baidu.com",params,file);
// HttpRequester.post("", params, null);
}
/**
* 利用
* (资源包)httpcomponents-asyncclient-4.0根据包下面的内容显示,
* pairms.add(new BasicNameValuePair("id", "988"));//服务器端
pairms.add(new BasicNameValuePair("name", "老梁"));
pairms.add(new BasicNameValuePair("method", "save"));
* 两种做方法
* */
//通过HhttpClien发送Post请求
public void testSendPostParamFromHttpClient() throws Exception {
HttpPost httpPost = new HttpPost("");//请求参数,指服务器地址。
List<NameValuePair> pairms = new ArrayList<NameValuePair>();//参娄
pairms.add(new BasicNameValuePair("id", "988"));//服务器端
pairms.add(new BasicNameValuePair("name", "老梁"));
pairms.add(new BasicNameValuePair("method", "save"));
//代表数据部分
httpPost.setEntity(new UrlEncodedFormEntity(pairms, HTTP.UTF_8));
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpPost);
response.getEntity().getContent();
// Log.i(TAG, result);
}
// 读取服务器信息
//自定义发送Post请求
public void testSendPostParam() throws Exception {
// 这里放的服务器地址,我们可以把JAVA写的项目眼布起来,一样都可以使用。
String path = "http:www.baidu.com";
Map<String, String> params = new HashMap<String, String>();
params.put("methos", "save");
params.put("id", "29832");
params.put("name", "老梁");
String result = NetTool.getTextContent(NetTool.sendPostRequest(path,params,"UTF-8"), "UTF-8");
Log.i(TAG, result);
}
}
package com.smart.activity;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import android.os.Environment;
import android.test.AndroidTestCase;
import android.util.Log;
import com.smart.domain.Resource;
import com.smart.net.utils.NetTool;
import com.smart.net.utils.SAXResourceService;
public class GetXMLTest extends AndroidTestCase {
private static final String TAG = "GetXMLTest";
public void testGetXML() throws Exception {
// 如果参数是中文,必须进行Url编码
String path = "http://211.143.108.6/wap/ResCatService?act=pic&s=h";
// String xml = NetTool.getTextContent(NetTool.getContent(path), "UTF-8");
String xml = NetTool.getTextContent2(path, "UTF-8");
FileOutputStream outStream=new FileOutputStream(new File(Environment.getExternalStorageDirectory(),"test.xml"));
OutputStreamWriter writer=new OutputStreamWriter(outStream,"UTF-8");
writer.write(xml);
writer.flush();//一定写进这个方法,要不然,写到内容里面就会没有写入文本
outStream.close();
// Log.i(TAG, xml);
}
//这种性能会差一点
public void testGetXMLAndParser() throws Exception {
// 如果参数是中文,必须进行URI编码
String path = "http://211.143.108.6/wap/ResCatService?act=pic&s=h";
String xml = NetTool.getTextContent(NetTool.getContent(path), "UTF-8");
InputStream inStream=new ByteArrayInputStream(xml.getBytes());
Resource resource=SAXResourceService.readXml(inStream);
Log.i(TAG, resource.toString());//打印出来XML文件的资源
}
/**
*
*
* */
// public void testGetXMLAndParset() throws Exception{
// String path="";
// String xml=Net
// }
//这种调用方法效果相对来讲会好一点
public void testGetXMLAndParser2() throws Exception {
// 如果参数是中文,必须进行URI编码
String path = "http://211.143.108.6/wap/ResCatService?act=pic&s=h";
InputStream inStream = NetTool.getContent(path);//
// InputStream inStream=new ByteArrayInputStream(xml.getBytes());
if(inStream!=null){
Resource resource=SAXResourceService.readXml(inStream);
Log.i(TAG, resource.toString());//打印出来XML文件的资源
}else{
Log.i(TAG, "----------->ERROR");
}
}
}