百度地图API 云存储·LBS.云 跨域问题解决方法——通过java.net.URLConnection发送HTTP请求
运用原生Java Api发送简单的Get请求、Post请求
HTTP请求一般为两种,一种是GET请求,一种是POST请求。
使用Java发送这两种请求步骤如下:
- 通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
- 设置请求的参数
- 发送请求
- 以输入流的形式获取返回内容
- 关闭输入流
根据上面步骤封装成HttpRequestor.java 工具类 网上参考代码很多,下面为调试并优化过的代码,修复了乱码等问题
package com.xeonmic.lbs.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
public class HttpRequestor {
private String charset = "utf-8";
private Integer connectTimeout = null;
private Integer socketTimeout = null;
private String proxyHost = null;
private Integer proxyPort = null;
/**
* Do GET request
* @param url
* @return
* @throws Exception
* @throws IOException
*/
public String doGet(String url) throws Exception {
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (reader !=