Http的GET请求与POST请求调用接口


GET请求

public static String doGet(Map<String, String> mapparams) {
        // 返回对象
        String result = "";
        
        try {
            // 传参
            JSONObject jsonObject = JSONObject.fromObject(mapparams);
            
            // 路径及参数
            String fasd = "?"+"InParam"+"="+URLEncoder.encode(jsonObject.toString(),"UTF-8");
            String getUrl =url+fasd;
            
            // http GET调用
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(getUrl);
            HttpResponse response = httpclient.execute(httpget);

            // 状态码
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                // 返回值
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }else{
                System.err.println("mapparams>>"+mapparams);
                result="{\"status\":\"FAILED\",\"errorMessage\":\""+EntityUtils.toString(response.getEntity(),"UTF-8")+"\"}";
            }

            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.err.println("mapparams>>"+mapparams);
            e.printStackTrace();
        }

        return result;
    }

POST:
public static String doPost(String url,Map<String, Object> mapparam) {

        String result = "";
        try {
            // 路径
            url = url;
            
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            
            // mapparam 参数
            String json = JsonConvert.objectToJson(mapparam);
            StringEntity se = new StringEntity(json,"UTF-8");
            se.setContentType("application/json");
            se.setContentEncoding("UTF-8");
            httpPost.setEntity(se);
            HttpResponse response = httpclient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }else{
                System.err.println("mapparams>>"+mapparam);
                result="{\"TYPE\":\"E\",\"errorMessage\":\""+status+"\"}";
            }
            
            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.err.println("mapparams>>"+mapparam);
            result="{\"TYPE\":\"E\",\"errorMessage\":\""+"接口不通"+"\"}";
            e.printStackTrace();
        }
        return result;

    }

public static String doPostJson(String url,Map<String, Object> mapparam) {

    String result = "";
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
        // 表单参数传递nvps
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();
        if(mapparam.containsKey("imgpath1")){
            nvps.add(new BasicNameValuePair("imgpath1", mapparam.get("imgpath1").toString()));
        }
        
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();
        if(status == HttpStatus.SC_OK){
            
            result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }else{
            System.err.println("mapparams>>"+mapparam);
            result="{\"TYPE\":\"E\",\"errorMessage\":\""+status+"\"}";
        }
        
        httpclient.getConnectionManager().shutdown();
    } catch (Exception e) {
        System.err.println("mapparams>>"+mapparam);
        result="{\"TYPE\":\"E\",\"errorMessage\":\""+"接口不通"+"\"}";
        e.printStackTrace();
    }
    return result;

}

public static String httpURLConnectionPOST(String POST_URL,String param) {
  	 StringBuilder sb = new StringBuilder(); // 用来存储响应数据  
      try {
          URL url = new URL(POST_URL);  
          // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中  
          // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)  
          connection.setDoOutput(true);  
          // 设置连接输入流为true  
          connection.setDoInput(true);  
          // 设置请求方式为post  
          connection.setRequestMethod("POST");  
          // post请求缓存设为false  
          connection.setUseCaches(false);  
          // 设置该HttpURLConnection实例是否自动执行重定向  
          connection.setInstanceFollowRedirects(true);  
          // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)  
          // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据  
          // ;charset=utf-8 必须要,不然会出现乱码【★★★★★】  
          connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");     
          // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)  
          connection.connect();  
          // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  
          DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
          // 将参数输出到连接  
          dataout.writeBytes("param="+param);  
          // 输出完成后刷新并关闭流  
          dataout.flush();  
          dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)   
          // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)  
          BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
          String line;  
         
          // 循环读取流,若不到结尾处  
          while ((line = bf.readLine()) != null) {  
              sb.append(line).append(System.getProperty("line.separator"));  
          }  
          bf.close();    // 重要且易忽略步骤 (关闭流,切记!)   
          connection.disconnect(); // 销毁连接  
          
      } catch (Exception e) {  
          e.printStackTrace();  
      } 
      return sb.toString();
  }











  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中调用HTTP接口POST请求,可以使用Java标准库中的`java.net.HttpURLConnection`类。 示例代码如下: ``` import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { public static void main(String[] args) { try { // 指定接口地址 URL url = new URL("http://your-interface-address"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方式 conn.setRequestMethod("POST"); // 设置请求头 conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); // 构造请求参数 String data = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; // 发送请求 DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); // 获取响应 int responseCode = conn.getResponseCode(); System.out.println("Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 需要注意的是, 需要引入相应的包,上述代码需要用到URL, HttpURLConnection, DataOutputStream,BufferedReader等类 其中,参数 `data` 是请求的参数,格式为字符串。 通过上述代码可以发送一个 POST 请求,可以在响应的基础上进一步操作

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值