JAVA post和get方式请求远程HTTP接口

java发送http协议 一般对方都会限定post或者get 这里就是可用的方法

首先是POST方式
传入参数为json 可改为任何类型

public class HttpPost implements Runnable {

    private String url_str;

    public HttpPost () {

    }

    public HttpPost (String url, boolean isPost) {
        this.url_str = url;
    }

    @Override
    public void run() {
        JSONObject param_json = new JSONObject();

        URL url = null;
        PrintWriter send_out = null;
        BufferedReader send_in = null;
        String result = "";
        try {
            //----------------------------------------------------------//
            //http://blog.csdn.net/thl331860203/article/details/51783434//
            //JAVA POST请求远程HTTP接口                                   //
            //----------------------------------------------------------//
            url = new URL(this.url_str);
            //打开和URL之间的连接 
            URLConnection connection = url.openConnection();
            //设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            end_out = new PrintWriter(connection.getOutputStream());
       //发送请求参数 
            send_out.print(param_json);
            //flush输出流的缓冲 
            send_out.flush();//定义BufferedReader输入流来读取URL的响应
            send_in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while((line = send_in.readLine()) != null){
                result += line;
            }
            getResultData(result);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getResultData(String result) {
    }
}

接下来是Get方式

public class HttpGet implements Runnable {

    private String url_str;public HttpGet() {

    }

    public HttpGet(String url, boolean isPost) {
        this.url_str = url;
    }

    @Override
    public void run() {
        JSONObject param_json = new JSONObject();

        URL url = null;
        PrintWriter send_out = null;
        BufferedReader send_in = null;
        String result = "";
        try {
            //----------------------------------------------------------//
            //http://blog.csdn.net/thl331860203/article/details/51783434//
            //JAVA POST请求远程HTTP接口                                   //
            //----------------------------------------------------------//
            url = new URL(this.url_str);
            //打开和URL之间的连接 
            URLConnection connection = url.openConnection();
            //设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//建立连接
            connection.connect();
            //定义BufferedReader输入流来读取URL的响应
            send_in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while((line = send_in.readLine()) != null){
                result += line;
            }
            getResultData(result);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getResultData(String result) {

    }
}

关于实现

HttpGet test = new HttpGet("");
Thread thread = new Thread(test);
thread.start();

因为JAVA在某版本之后 为了防止协议没有响应 所以不允许直接使用这个方法 一定要在子线程中使用
以上除了部分代码以外都是自己的理解 如果不对 请指出 谢谢

Java可以使用HTTPClient和HttpURLConnection两种方式来实现GET和POST请求。 使用HTTPClient的方法有两个版本,分别是HTTPClient3.1和HTTPClient4.5.5。HTTPClient3.1位于org.apache.commons.httpclient包下,而HTTPClient4.5.5位于org.apache.http.client包下。这两个版本都提供了对远程URL的操作工具包,可以满足工作需求。 另一种方式是使用HttpURLConnection,它是Java的标准请求方式。可以通过创建HttpURLConnection对象来发送GET和POST请求,并获取响应结果。 以下是使用HTTPClient和HttpURLConnection实现GET和POST请求的示例代码: 使用HTTPClient3.1实现GET请求: ```java HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); String response = method.getResponseBodyAsString(); ``` 使用HTTPClient4.5.5实现GET请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现GET请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 使用HTTPClient4.5.5实现POST请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); request.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现POST请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("param1=value1&param2=value2"); writer.flush(); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 以上是使用Java实现GET和POST请求的方法,可以根据具体需求选择适合的方式发送请求并获取响应结果。\[1\]\[2\] #### 引用[.reference_title] - *1* [用Java实现GET,POST请求](https://blog.csdn.net/lianzhang861/article/details/80364549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [JAVA的GET和POST请求实现方式](https://blog.csdn.net/u012513972/article/details/79569888)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值