java模擬post請求發送json數據



import com.alibaba.fastjson.JSONObject; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL;
public class HttpRequest2 { public static String sendPost(String url,String param){ OutputStreamWriter out =null; BufferedReader reader = null; String response = ""; //創建連接 try { URL httpUrl = null; //HTTP URL類 用這個類來創建連接 //創建URL httpUrl = new URL(url); //建立連接 HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("connection", "keep-alive"); conn.setUseCaches(false);//設置不要緩存 conn.setInstanceFollowRedirects(true); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); //POST請求 out = new OutputStreamWriter( conn.getOutputStream()); out.write(param); out.flush(); //讀取響應 reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); response+=lines; } reader.close(); // 斷開連接 conn.disconnect(); } catch (Exception e) { System.out.println("發送 POST 請求出現異常!"+e); e.printStackTrace(); } //使用finally塊來關閉輸出流、輸入流 finally{ try{ if(out!=null){ out.close(); } if(reader!=null){ reader.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return response; } public static String sendPost2(String url, String data) { String response = null; try { CloseableHttpClient httpclient = null; CloseableHttpResponse httpresponse = null; try { httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8")); httppost.setEntity(stringentity); httpresponse = httpclient.execute(httppost); response = EntityUtils .toString(httpresponse.getEntity()); } finally { if (httpclient != null) { httpclient.close(); } if (httpresponse != null) { httpresponse.close(); } } } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) { JSONObject jsonParam = new JSONObject(); jsonParam.put("id", "12306"); jsonParam.put("name", "zhangsan"); String param = jsonParam.toJSONString(); String url="http://localhost:8080/demo/one"; String sendPost = sendPost2(url, param); System.out.println(sendPost); } }

下面是后台的代碼

@RestController
@RequestMapping("/demo")
public class PostController {

    @Resource
    protected HttpServletRequest request;

    @RequestMapping(value = "/one",method = RequestMethod.POST)
    public String getResult(String str)throws Exception{

        InputStreamReader reader = new InputStreamReader(request.getInputStream(),"UTF-8");
        char[] buff = new char[1024];
        int length =0;
        while((length =reader.read(buff))!=-1){
            String message = new String(buff,0,length);
            System.out.println("接收到的信息   "+ message);
        }

        return JSON.toJSONString("這是post請求");
    }
}

 依賴的jar包

 <!--http 請求需要的jar包-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM