java实现:http协议get和post方法的url参数请求响应及交互

http协议get方法请求:

/**
     * 请求数据    Get方法请求参数
     * @param values 参数
     * @param url 
     * @return 返回值
     */
    @SuppressWarnings({ "resource", "deprecation" })
    public static JSONObject doGet(List<BasicNameValuePair> values, String url) {
     
        HttpClient client = new DefaultHttpClient();//申明一个网络访问客户端  
        String tmpUrl = url + "?" + values.get(0);
        HttpGet httpget = new HttpGet(tmpUrl);//post方式  
        String resp = null;
        JSONObject jsStr = null;
        try {
            HttpResponse response = client.execute(httpget);//响应结果  
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                
                resp = EntityUtils.toString(resEntity);
                jsStr = JSONObject.fromObject(resp);
                EntityUtils.consume(resEntity);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }

        return jsStr;
    }

http协议post方法请求:

/**
     * 请求数据
     * @param values 参数
     * @param url 
     * @return 返回值
     */
    @SuppressWarnings({ "resource", "deprecation" })
    public static JSONObject doPost(List<BasicNameValuePair> values, String url) {
     
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        String resp = null;
        JSONObject jsStr = null;
        
        try {
            httppost.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8));
            HttpResponse response = client.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                resp = EntityUtils.toString(resEntity, "UTF-8");
                System.out.println(resp);
                jsStr = JSONObject.fromObject(resp);
                EntityUtils.consume(resEntity);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }

        return jsStr;
    }

其中:

         List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
            try {
                values.add(new BasicNameValuePair("param", data));//param参数名称,data为发送数据
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //发送信息,接收回复
            JSONObject jsonData = doPost(values, CodeConsts.COUPONS_CONFIRM_URL);//CodeConsts.COUPONS_CONFIRM_URL为url常量



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中可以使用HttpURLConnection或者Apache HttpClient来发送HTTP请求。其中,HttpURLConnection是Java标准库中提供的类,它可以通过向服务器发送不同的HTTP请求方法(如GET、POST等)来实现与服务器的交互。Apache HttpClient是一个第三方库,相对于HttpURLConnection来说,它提供了更多的功能和更简洁的API接口。 下面以HttpURLConnection为例介绍如何发送POST请求: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class HttpPostExample { public static void main(String[] args) throws IOException { String url = "http://example.com/api/v1/user"; // 请求url地址 String body = "{\"username\":\"test\",\"password\":\"123456\"}"; // 请求URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // 设置请求方法POST con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // 设置请求头 con.setDoOutput(true); // 允许输出流 // 发送请求体 try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8); wr.write(bodyBytes); wr.flush(); } // 处理响应结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } System.out.println("Response Body : " + response.toString()); } } } ``` 以上代码演示了如何使用HttpURLConnection发送POST请求,其中`url`表示请求url地址,`body`表示请求体,需要根据实际情况进行修改。在发送请求时,需要设置请求方法POST,并设置请求头`Content-Type`为`application/json; charset=UTF-8`。在发送请求体后,可以通过`getResponseCode`方法获取响应状态码,通过`getInputStream`方法获取响应内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值