java后台发送get,post请求、将String转化为json

/**
	 * 发送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;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值