public class HttpUtil {
// private static HttpClient client = new DefaultHttpClient();
private static final String CHARSET = HTTP.UTF_8;
private static HttpClient client;
private static synchronized HttpClient getHttpClient() {
if (null == client) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 20000);
// /* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 20000);
// /* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 20000); //
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https",
org.apache.http.conn.ssl.SSLSocketFactory
.getSocketFactory(), 443)); //
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
client = new DefaultHttpClient(conMgr, params);
}
return client;
}
/**
* get方式与服务器端交互
*
* @param url
* @return
* @throws Exception
*/
public static String getRequest(String url) throws Exception {
HttpGet get = new HttpGet(url);
getHttpClient();
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
return null;
}
/**
* post方式与服务器端交互数据
*
* @param url
* @param params
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static String postRequest(String url, Map<String, Object> rawParams)
throws Exception {
HttpPost post = new HttpPost(url);
getHttpClient();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 封装请求参数
for (String key : rawParams.keySet()) {
params.add(new BasicNameValuePair(key, rawParams.get(key)
.toString()));
}
// 设置请求参数
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
// 返回结果字符串
String result = EntityUtils.toString(response.getEntity());
return result;
}
return null;
}
public static void main(String[] args) throws Exception {
String json = HttpUtil
.getRequest("http://api.map.baidu.com/geocoder?address=上海市浦东新区陆家嘴&output=json&key=ab6bbb8dffddae6765c6bfab8fe49abd&city=上海");
System.out.println(json);
JSONObject o=JSONObject.fromObject(json);
JSONObject result=o.optJSONObject("result");
JSONObject location=result.optJSONObject("location");
System.out.println(location.getString("lng"));
}
}
与服务器端链接的工具类
最新推荐文章于 2022-06-23 09:41:56 发布