使用到的jar:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
工具方法:
public class HttpRequest { private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class); public static String httpRequest(String httpUrl, String requestMethod,String outputStr) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(httpUrl); URLConnection rulConnection = url.openConnection(); HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection; httpUrlConnection.setDoOutput(true); httpUrlConnection.setDoInput(true); httpUrlConnection.setUseCaches(false); httpUrlConnection.setRequestProperty("Content-Type", "application/json"); httpUrlConnection .setRequestProperty("POST", "/violations HTTP/1.1"); httpUrlConnection.setRequestMethod(requestMethod); httpUrlConnection.connect(); if (null != outputStr) { OutputStream outputStream = httpUrlConnection.getOutputStream(); outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } InputStream inputStream = httpUrlConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; httpUrlConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } }
调用方法:
String jsonString = HttpRequest.httpRequest(urlIn, “POST”, object.toString());
返回的是json格式字符串,通过解析结果串得到反馈结果。。。。。
[https://editor.csdn.net/md?not_checkout=1&articleId=121426949]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)