Java跨域请求代码

1、get请求的方式

get请求中,如果拼接的参数字符串中带有空格,后台会报错无法请求成功,适用于通过属性值查询对象接口。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;

public class UrlGetTest {

    public static void main(String[] args) {
        String url = "http://192.168.80.241:8080/choice-ERP/inf/currency/editInfo?"
                + "currency.CURRENCY_ID=19"
                + "&currency.IS_STANDARD=2"
                + "&currency.C_UUID=4028c664659ed4b701659ed6849e09bf"
                + "&currency.CURRENCY_CODE=CBA"
                + "&currency.STATUS=1"
                + "&currency.CURRENCY_CNAME=测试币种cba" 
                + "&currency.CURRENCY_ENAME=null"
                + "&currency.CREATE_TIME=2018-08-31%22:00:00"
                + "&currency.CREATE_USER=导入";
        System.out.println(getToInfo(url));

    }
    
    public static JSONObject getToInfo(String urlStr) {
        String msg = "";
        try {
            // 1. 得到访问地址的URL
//            URL url = new URL("http://win7-20180115nd:8080/choice-ERP/warehouse/infFindByWareHouseID?WAREHOUSE_ID=1");
            URL url = new URL(urlStr);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            /* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
            // 设置是否向HttpURLConnection输出
            connection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            connection.setDoInput(true);
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 设置是否使用缓存
            connection.setUseCaches(true);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            connection.setInstanceFollowRedirects(true);
            // 设置超时时间
            connection.setConnectTimeout(3000);
            // 连接
            connection.connect();
            // 4. 得到响应状态码的返回值 responseCode
            int code = connection.getResponseCode();
            // 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据
            
            if (code == 200) { // 正常响应
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = null;

                while ((line = reader.readLine()) != null) { // 循环从流中读取
                    msg += line + "\n";
                }
                reader.close(); // 关闭流
            }
            // 6. 断开连接,释放资源
            connection.disconnect();

            // 显示响应结果
//            System.out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
            msg = "{\"isSuccess\":false,\"msg\":\"System Error:"+ e.getMessage() +"\"}";
        }
        return JSONObject.parseObject(msg);
        
    }

}
2、post请求的方式

post请求用于传输数据,适用于数据表的增删改

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;

public class PostUrlTest {

    public static void main(String[] args) throws Exception {
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("isSuccess", true);
//        System.out.println(jsonObject.get("isSuccess"));
        
//        Map<String, Object> params = new HashMap<>();
//        JSONObject params= new JSONObject(); 
//        params.put("warehouse.WAREHOUSE_ID", 45);
//        params.put("warehouse.WAREHOUSE_CODE", "CBA-002");
//        params.put("warehouse.C_UUID", "40284c81655f972c01655f9ab4eb0001");
        StringBuilder sb = new StringBuilder();
        sb.append("warehouse.WAREHOUSE_ID=80&");
        sb.append("warehouse.WAREHOUSE_CODE=CBA-002&");
        sb.append("warehouse.C_UUID=40284c81655f972c01655f9ab4eb0001");
        
        String url = "http://win7-20180115nd:8080/choice-ERP/inf/warehouse/editInfo";
        String result = jsonPost1(url, sb.toString());
        System.out.println(result);
        
        /*try {
            int a = 1/0;
            System.out.println(a);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }*/
        
        /*List<Map<String, Object>> createQueue = new FQueueServiceImpl().createQueue();
        System.out.println(createQueue.get(0));*/
    }
    
    /**
     * 使用json字符串的格式传输数据
     * @param strURL
     * @param params
     * @return
     */
    public static String jsonPost(String strURL, String params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            String param = JSONUtils.toJSONString(params);
            out.append(param);
            out.flush();
            out.close();
 
            int code = connection.getResponseCode();
            InputStream is = null;
            if (code == 200) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }
            int contentLength = connection.getContentLength();
            // 读取响应
            int length = (int) contentLength;// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                return result;
            }
 
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }
    
    /**
     * 使用字符串的格式传输数据
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String jsonPost1(String url, String params) throws Exception {
             HttpPost httpPost = new HttpPost(url);  
            StringEntity stringEntity = new StringEntity(params);
            stringEntity.setContentType("application/x-www-form-urlencoded");  
            httpPost.setEntity(stringEntity);  
            DefaultHttpClient client = new DefaultHttpClient();   
            HttpResponse httpResponse = client.execute(httpPost);  
            String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);  
            return result;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值