package forrest.cartoon.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
/**
* String url = HttpUtil.get(
* "http://192.168.1.107/cartoonReader/cartoon/book/type.php?action=type");
*/
public static String get(String url) {
HttpGet get = new HttpGet(url); // 创建HttpGet
HttpClient client = new DefaultHttpClient(); // 取得默认的HttpClient
try {
HttpResponse response = client.execute(get); // 用HttpClient的execute方法执行HttpGet请求,返回HttpResponse
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 查看返回码是否为200
String result = EntityUtils.toString(response.getEntity()); // EntityUtils.toString,内容为response.getEntity实体
return result; // 返回实体的String字符串
} else {
return "读取失败";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Map<String, String> map = new HashMap<String, String>();
* map.put("action", "type"); String content = HttpUtil.post(
* "http://192.168.1.107/cartoonReader/cartoon/book/type.php", map);
*/
public static String post(String url, Map<String, String> map) { // url地址,
// map为请求值的键值队
HttpPost post = new HttpPost(url); // 创建HttpPost
HttpClient client = new DefaultHttpClient(); // 取得默认的HttpClient
List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // 创建list
try {
if (map != null) { // 如果map不为null
Iterator<Entry<String, String>> it = map.entrySet().iterator(); // map转化为set集合,并创建迭代器
while (it.hasNext()) { // 迭代器有下一个元素
Entry<String, String> entry = (Entry<String, String>) it.next(); // 从迭代器中取出下一个元素,强转为entry
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); //
}
HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
post.setEntity(entity);
}
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (Exception e) {
e.getMessage();
}
return url;
}
}
HttpUtil
最新推荐文章于 2020-08-18 23:26:44 发布