http post/get 请求

Posted phyxis_xu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了http post/get 请求相关的知识,希望对你有一定的参考价值。

get 请求

publicvoid sendSms() throws Exception{
        String message="货已发到";
        message=URLEncoder.encode(message, "UTF-8");
        System.out.println(message);
        String path ="http://localhost:8083/DS_Trade/mobile/sim!add.do?message="+message;
        URL url =new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5*1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();    
        byte[] data = StreamTool.readInputStream(inStream);
        String result=new String(data, "UTF-8");
        System.out.println(result);
    }

 

post 请求

public static void addByUrl() throws Exception{
        String encoding="UTF-8";
        String params="{‘result‘:‘123456‘}";
        String path ="http://localhost/ClientData_Collection/getStatus";
        byte[] data = params.getBytes(encoding);
        URL url =new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
        conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5*1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        System.out.println(conn.getResponseCode()); //响应代码 200表示成功
        if(conn.getResponseCode()==200){
            InputStream inStream = conn.getInputStream();   
            //String result=new String(inputStream2String(inStream), "UTF-8");
        }
    }

 

以上是关于http post/get 请求的主要内容,如果未能解决你的问题,请参考以下文章

HTTP 请求:GET vs. POST

在线HTTP POST/GET模拟请求api接口http请求测试工具https://post.jsonin.com/

HTTP 请求的 GET 与 POST 方式的区别

HTTP Basic Auth 的 POST / GET / PUT / DELETE 请求 By Java

HTTP Basic Auth 的 POST / GET / PUT / DELETE 请求 By Java

C#用HttpClient类post get,怎么设置cookies