JAVA 調用HTTPPOST請求__WEB

來源:互聯網
上載者:User
import java.util.ArrayList;import java.util.List;import org.apache.http.Header;import org.apache.http.message.BasicHeader;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;public class HttpRequestDemo {private String baseUrl;    private HttpClient httpClient;        @Before    public void setUp() {        baseUrl = "http://localhost:8087/???";        httpClient = HttpClientBuilder.create().build();    }@Test    public void testSend() throws Exception {        String body = JSON.toJSONString(參數);        HttpPost req = new HttpPost(baseUrl);        List<Header> headers = new ArrayList<Header>();        headers.add(new BasicHeader("頭部資訊", 值));        req.setHeaders(headers.toArray(new Header[0]));        req.addHeader(HTTP.CONTENT_TYPE, "application/json");//請求參數為JSON格式        StringEntity entity = new StringEntity(body, "UTF-8");        req.setEntity(entity);                HttpResponse resp = httpClient.execute(req);        HttpEntity respEntity = resp.getEntity();//獲得返回資料        String text = EntityUtils.toString(respEntity, "UTF-8");                JSONObject obj = (JSONObject) JSONObject.parse(text);        assertEquals(true, obj.get("success"));    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.