package com.jzlg.asyncexam;java
import java.util.ArrayList;apache
import java.util.List;async
import java.util.Map;this
import java.util.Set;url
import org.apache.http.HttpResponse;spa
import org.apache.http.client.HttpClient;code
import org.apache.http.client.methods.HttpGet;orm
import org.apache.http.client.utils.URLEncodedUtils;rem
import org.apache.http.impl.client.DefaultHttpClient;get
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class InternetHelper {
// 發送請求
public String requestUrl(String url, Map<String, Object> map) {
// 抓換參數
try {
//轉換參數
String params = cdtParams(map);
//建立請求客戶端
HttpClient httpClient = new DefaultHttpClient();
//建立get請求
HttpGet doGet = new HttpGet(url + "?" + params);
//發送請求,並返回 response
HttpResponse response = httpClient.execute(doGet);
if (response != null) {
//獲取並轉換相應的結果
return EntityUtils.toString(response.getEntity());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
// 轉換參數
private String cdtParams(Map<String, Object> map) {
// 處理參數
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
Set<String> keys = map.keySet();
for (String key : keys) {
params.add(new BasicNameValuePair(key, map.get(key).toString()));
}
// 將參數轉換
return URLEncodedUtils.format(params, "UTF-8");
}
}
//Post請求
package com.jzlg.inter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class internetHeper {
//發送請求若是發送的參數帶有參數通常使用Post請求
public String request(String url,Map<String, Object> map)
{
try {
List<BasicNameValuePair> parem=this.Parem(map);
//建立客戶端
HttpClient httpClient=new DefaultHttpClient();
//建立請求方式
HttpPost httpPost=new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(parem,"UTF-8"));
//得到響應
HttpResponse response=httpClient.execute(httpPost);
if(response!=null)
{
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//轉換參數
public List<BasicNameValuePair> Parem(Map<String , Object> map)
{
List<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>();
Set<String> keys=map.keySet();
for(String key:keys)
{
list.add(new BasicNameValuePair(key,map.get(key).toString()));
}
//將參數轉換
return list;
}
}