//一、post JsonObject // public static String post(JSONObject json,String URL) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(URL); post.setHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Basic YWRtaW46"); String result = ""; try { StringEntity s = new StringEntity(json.toString(), "utf-8"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); // 发送请求 HttpResponse httpResponse = client.execute(post); // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8")); StringBuilder strber = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) strber.append(line + "\n"); inStream.close(); result = strber.toString(); System.out.println(result); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { System.out.println("请求服务器成功,做相应处理"); } else { System.out.println("请求服务端失败"); } } catch (Exception e) { System.out.println("请求异常"); throw new RuntimeException(e); } return result; } /** 二、 * 使用post方法访问url * @param url_str * @param data_str * @return url返回的结果集 */ public static String operate(String url_str, String data_str) { String result = "";// 结果集 String sc = ""; // 中间提取流中一行的数据 System.out.println("准备请求:" + url_str + data_str);// 查看完整url OutputStreamWriter out = null; BufferedReader br = null; try { URL url = new URL(url_str); // 打开跟url之间的连接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); // 设置可以发送数据 con.setDoOutput(true); // 设置可以接收数据 con.setDoInput(true); // 设置post方式请求 con.setRequestMethod("POST"); /* con.setRequestMethod("GET"); //设置get方式请求 */ // 使用OutputStreamWriter获取URLConnection对象对应的输出流 ,采用默认编码格式 out = new OutputStreamWriter(con.getOutputStream(), "utf-8"); // 发送请求数据 out.write(data_str); // 避免缓冲造势、flush输出流中的缓冲区 out.flush(); // 处理结果集,读取url的响应,采用默认编码格式 br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8")); //通过中间变量、每次读取一行、读取到null时停止 while ((sc = br.readLine()) != null) { result = result + sc;//拼接字符串 } } catch (Exception e) { System.out.println(e.getMessage());// 输出错误信息 } finally { try { if (out != null) { out.close(); } if (br != null) { br.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } // 打印返回结果 System.out.println("返回结果:" + result); return result;//返回结果集 }
Java实现发送两种post请求
最新推荐文章于 2024-05-10 14:52:23 发布