您好,登錄后才能下訂單哦!
這篇文章給大家介紹Java中怎么發送HTTP請求,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
import java.net.HttpURLConnection; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.databind.ObjectMapper;
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.8</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
HTTP 發送 get 請求
首先我們引入兩個包
發送get請求的工具類,可直接 copy 使用即可
另外,我拋出異常的代碼大家改成自己業務的異常,不需要就刪除掉。
參數說明:
host:ip
servUri:url
reString:參數
public static String getHttpData(String host, String servUri, String reString) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("getHttpData:host:" + host + ",servUri:" + servUri + ",reString:" + reString); String strResp = null; try { URI uri = new URIBuilder().setScheme("http").setHost(host).setPath(servUri) .setParameter("strInfo", reString).build(); HttpGet httpGet = new HttpGet(uri); CloseableHttpClient client3 = HttpClients.createDefault(); HttpResponse resp; resp = client3.execute(httpGet); if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { strResp = EntityUtils.toString(resp.getEntity()); logger.info("the return result:{}", strResp); } else { logger.info("Error Response:", resp.getStatusLine().toString()); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } } catch (Exception e) { logger.error(sb.toString() + ":" + e.getMessage(), e.getCause()); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } return strResp; }
HTTP 發送 post 請求
發送post分兩種,我分兩種的原因是為了讓大家方便,想傳對象和 json 可以直接復制過用就可以用,不用你們在轉了。
第一種是直接接收json
參數明說:
url:url
json:參數
public static String doPostData(String url, String json) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); String result = ""; HttpResponse res = null; try { StringEntity s = new StringEntity(json.toString(), "UTF-8"); s.setContentType("application/json"); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json; charset=utf-8"); post.setEntity(s); res = client.execute(post); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(res.getEntity()); return HttpStatus.SC_OK + ""; } } catch (Exception e) { if(res == null) { return "HttpResponse 為 null!"; } throw new RuntimeException(e); } if(res == null || res.getStatusLine() == null) { return "無響應"; } return res.getStatusLine().getStatusCode() + ""; }
@Test public void test12() throws Exception { String HOST = "http://eipwcf.aspirecn.com/SvcEF/Service1.svc/WCF_EF_MSA_GetDataInfo_P"; HttpClient client = new HttpClient(); JSONObject json = new JSONObject(); json.put("msgId", msgId); String reslut=client.doPostData(HOST, json); }
第二種是參數是對象
參數說明:
url:url
tram:對象
public static String doHttpPostData(String url, TaskReleaseApprovalModel tram) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("doHttpPostData:url:" + url + ",tram:" + tram.toString() + ",contentType:" + contentType); logger.info(sb.toString()); String tmpString = ""; HttpPost request = new HttpPost(url); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); ObjectMapper mapper = new ObjectMapper(); String jsonString; try { jsonString = mapper.writeValueAsString(tram); StringEntity entity = new StringEntity(jsonString, "UTF-8"); request.setEntity(entity); CloseableHttpClient client = HttpClients.createDefault(); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { tmpString = EntityUtils.toString(response.getEntity()); logger.info("the post result:tmpString:{}", tmpString); } else { logger.info("the post failure:tmpString:", tmpString); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } } catch (Exception e) { logger.error(sb.toString() + ":" + e.getMessage(), e.getCause()); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_POSTWCF, CommonConstants.TASK_RELEASE_POSTWCF_DESC); } return tmpString; }
關于Java中怎么發送HTTP請求就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。