1.今天调用了好多的程序,通过httpUrlConnection, 返回json,根据json进行操作。
好多细节,乱码问题是需要用UTF-8解码,
返回的数据不是json的形式,是因为post请求时没有申请请求的数据类型。
2.各种异步加载,我也是醉了,
3.需要了解js跨域。看到了jsonp,没看懂。
public class HttpURLConnectionUtil {
/**
* 获取的post请求
* @date 2015-11-23 下午2:28:39
* @param urlPath
* @return
*/
public static String getRequest(String urlPath, String data){
StringBuilder sBuilder = new StringBuilder();
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//可以传递对象,如果携程text/html对象无法传递
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setInstanceFollowRedirects(true);
if(data != null && StringUtils.isNotBlank(data)){
conn.setDoOutput(true);
conn.setDoInput(true);
conn.getOutputStream().write(data.getBytes("utf8"));
conn.getOutputStream().flush();
conn.getOutputStream().close();
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
while ((line = in.readLine()) != null) {
sBuilder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return sBuilder.toString();
}
/**
* 发送图片上传的请求,支持数组数据的提交
* @date 2015-8-25 上午11:11:12
* @param url
* @param files
* @param map
* @return
* @throws IOException
*/
public static String commitWithFiles(String url, List<File> files, Map<String, String[]> map, String uploadName) {
String result = "";
String boundary = UUIDUtil.getUUID();
if (map == null) {
map = new HashMap<String, String[]>();
}
try {
HttpURLConnection conn = getBaseConnection(url, boundary);
if (null == conn) {
return result;
}
// 连接
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//输出基本参数
writeBaseParam(out, files, map, boundary);
//输出文件参数
writeFileParam(out, files, boundary, uploadName);
out.flush();
out.close();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println(conn.getResponseCode());
return result;
}
//获取返回的结果
result= getResult(conn);
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 单个发送图片上传的请求,支持数组数据的提交
* @date 2015-8-25 上午11:58:42
* @param url
* @param file
* @param map
* @return
*/
public static String commitWithFile(String url, File file, Map<String, String[]> map, String uploadName) {
List<File> files = new ArrayList<File>();
files.add(file);
return commitWithFiles(url, files, map, uploadName);
}
/**
* 检验url地址是否正确
* @date 2015-8-25 上午11:10:50
* @param url
* @return
*/
public static String checkUrl(String url) {
String result = url;
if (url.startsWith("http://")) {
url = url.replaceFirst("http://", "");
if (url.contains("//")) {
url = url.replaceAll("//", "/");
}
result = "http://" + url;
}else{
result = "http://" + url;
}
result = result.replaceAll(":", ":").replaceAll(":", ":").replaceAll(" ", "");
return result;
}
/**
* 根据url获取连接
* @date 2015-8-25 上午11:25:29
* @param url
* @return
*/
private static HttpURLConnection getBaseConnection (String url, String boundary) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) (new URL(checkUrl(url)).openConnection());
conn.setReadTimeout(1000000);
conn.setConnectTimeout(1000000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setInstanceFollowRedirects(true);
conn.setChunkedStreamingMode(10240);
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 输出基本的参数
* @date 2015-8-25 上午11:32:48
* @param out
* @param files
* @param map
* @param boundary
*/
private static void writeBaseParam (DataOutputStream out, List<File> files, Map<String, String[]> map, String boundary) {
// 普通参数
StringBuffer sb = new StringBuffer();
// 文件名称
for (File file : files) {
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"uploadFileNames\"\r\n\r\n");
sb.append(file.getName() + "\r\n");
sb.append("--" + boundary + "\r\n");
}
// 其他参数
for (String key : map.keySet()) {
String name = key;
String[] vals = (String[]) map.get(key);
for (String val : vals) {
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + name
+ "\"\r\n\r\n");
sb.append(val + "\r\n");
sb.append("--" + boundary + "\r\n");
}
}
try {
out.write(sb.toString().getBytes("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 输出文件参数
* @date 2015-8-25 上午11:33:28
* @param out
* @param files
* @param boundary
*/
private static void writeFileParam (DataOutputStream out, List<File> files, String boundary, String uploadName) {
FileInputStream in = null;
// 文件
for (File file : files) {
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("--" + boundary + "\r\n");
strBuffer.append("Content-Disposition: form-data; name=" + uploadName + "; filename="+ file.getName() + "\r\n");
strBuffer.append("Content-Type: application/octet-stream\r\n");
strBuffer.append("\r\n");
try {
in = new FileInputStream(file);
out.write(strBuffer.toString().getBytes());
byte[] buffer = new byte[1024];
int hasRead = -1;
while ((hasRead = in.read(buffer)) != -1) {
out.write(buffer, 0, hasRead);
}
out.write("\r\n".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
try {
out.write(("--" + boundary + "--\r\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getResult (HttpURLConnection conn) {
String result = "";
String temp = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((temp = reader.readLine()) != null) {
result += temp;
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
越努力,越幸运