/**
* 发送GET请求并返回结果
* @param url
* @return
*/
public Map requestGet(String url) {
try {
//得到字节流
InputStream in = new URL(url).openStream();
//将字节流转化成字符流,并指定字符集
InputStreamReader isr = new InputStreamReader(in,"UTF-8");
//将字符流以缓存的形式一行一行输出
BufferedReader bf = new BufferedReader(isr);
String results = "";
String newLine = "";
while((newLine = bf.readLine()) != null){
results += newLine+"\n";
}
Map<String, Object> map = new HashMap<String, Object>();
map = toMap(results);
return map;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 发送post请求
* @param url
* @param message
* @return
*/
//String params = "{\"user_ticket\": \""+user_ticket+"\"}";
public static String requestPost(String urls,String params) {
StringBuffer sb=new StringBuffer();
try {
// 创建url资源
URL url = new URL(urls);
// 建立http连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置不用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
params = params==null?"":params;
byte[] data = params.getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json");
// 开始连接请求
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream()) ;
// 写入请求的字符串
out.write(data);
out.flush();
out.close();
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
// 请求返回的数据
InputStream in1 = conn.getInputStream();
try {
String readLine=new String();
BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
while((readLine=responseReader.readLine())!=null){
sb.append(readLine).append("\n");
}
responseReader.close();
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("error++");
}
} catch (Exception e) {
}
return sb.toString();
}
/**
* 将Json类型的String字符串转换成Map
* @param jsonString
* @return
*/
public static Map toMap(String jsonString){
//需导入jar包
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = gson.fromJson(jsonString, map.getClass());
return map;
}