如何使用HttpClient发送java对象到服务器
这篇文章主要介绍了如何使用HttpClient发送java对象到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一、首先导入apache依赖的pom文件包
org.apache.httpcomponents httpclient
二、创建JavaBean实体类对象
publicclassFulFillMentimplementsBaseModel{ /** *shopify内部订单物理位置ID */ privateLonglocation_id; /** *运单号 */ privateStringtracking_number; /** *快递公司 */ privateStringtracking_company; /** *shopify平台内部商品id */ privateListline_items; publicLonggetLocation_id(){ returnlocation_id; } publicvoidsetLocation_id(Longlocation_id){ this.location_id=location_id; } publicStringgetTracking_number(){ returntracking_number; } publicvoidsetTracking_number(Stringtracking_number){ this.tracking_number=tracking_number; } publicStringgetTracking_company(){ returntracking_company; } publicvoidsetTracking_company(Stringtracking_company){ this.tracking_company=tracking_company; } publicList getLine_items(){ returnline_items; } publicvoidsetLine_items(List line_items){ this.line_items=line_items; } }
三、这里封装一个上传到服务器的Utils工具类
packagecom.glbpay.ivs.common.util.https; importcom.alibaba.fastjson.JSON; importorg.apache.http.HttpEntity; importjava.io.InputStream; importjava.io.OutputStream; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.methods.CloseableHttpResponse; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.entity.StringEntity; importorg.apache.http.impl.client.CloseableHttpClient; importorg.apache.http.impl.client.HttpClientBuilder; importorg.apache.http.util.EntityUtils; importjava.io.IOException; importjava.net.HttpURLConnection; importjava.net.MalformedURLException; importjava.net.URL; publicclassNewHttpClient{ publicstaticStringdoPost(Stringurl,Objectmyclass){ CloseableHttpClienthttpClient=HttpClientBuilder.create().build(); HttpPostposturl=newHttpPost(url); Stringresult=null; StringjsonSting=JSON.toJSONString(myclass); StringEntityentity=newStringEntity(jsonSting,"UTF-8"); posturl.setEntity(entity); posturl.setHeader("Content-Type","application/json;charset=utf8"); //响应模型 CloseableHttpResponseresponse=null; try{ //由客户端执行(发送)Post请求 +6response=httpClient.execute(posturl); //从响应模型中获取响应实体 HttpEntityresponseEntity=response.getEntity(); System.out.println("响应状态为:"+response.getStatusLine()); if(responseEntity!=null){ System.out.println("响应内容长度为:"+responseEntity.getContentLength()); System.out.println("响应内容为:"+EntityUtils.toString(responseEntity)); returnEntityUtils.toString(responseEntity); } }catch(ClientProtocolExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ //释放资源 if(httpClient!=null){ httpClient.close(); } if(response!=null){ response.close(); } }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } publicstaticStringdourl(Stringurl,Objectclzz){ try{ StringjsonString=JSON.toJSONString(clzz); URLurl1=newURL(url); HttpURLConnectionconn=(HttpURLConnection)url1.openConnection(); //设置允许输出 conn.setDoOutput(true); //设置允许输入 conn.setDoInput(true); //设置不用缓存 conn.setUseCaches(false); conn.setRequestMethod("POST"); //设置传递方式 conn.setRequestProperty("contentType","application/json"); //设置维持长连接 conn.setRequestProperty("Connection","Keep-Alive"); //设置文件字符集: conn.setRequestProperty("Charset","UTF-8"); //开始请求 byte[]bytes=jsonString.toString().getBytes(); //写流 OutputStreamstream=conn.getOutputStream(); stream.write(bytes); stream.flush(); stream.close(); intresultCode=conn.getResponseCode(); if(conn.getResponseCode()==200){ InputStreaminputStream=conn.getInputStream(); byte[]bytes1=newbyte[inputStream.available()]; inputStream.read(bytes1); //转字符串 Strings=newString(bytes); System.out.println(s); returns; }else{ //获取响应内容 intcode=conn.getResponseCode(); StringresponseMessage=conn.getResponseMessage(); System.out.println(code); Strings=String.valueOf(code); return"响应状态码是:"+s+"响应内容是:======="+responseMessage; } }catch(MalformedURLExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } }
开始调用
FulFillMentModelfulFillMentModel=newFulFillMentModel(); FulFillMentfulfillment=newFulFillMent(); fulfillment.setLocation_id(order.getLocationId()); fulfillment.setTracking_number(order.getTrackingNo()); fulfillment.setTracking_company(order.getChannelCode()); fulfillment.setLine_items(lineItemList); fulFillMentModel.setFulfillment(fulfillment); Stringurl=String.format("https://%s:%s@stuushop-com.myshopify.com/admin/api/2019-07/orders/%s/fulfillments.json",settingModel.getAppKey(),settingModel.getPassword(),order.getLastOrderId()); logger.info("shopify平台请求地址:{},请求数据:{}",url,JsonUtils.bean2json(fulFillMentModel)); Strings=NewHttpClient.doPost(url,fulFillMentModel); logger.info("shopify平台返回数据:{}",JsonUtils.bean2json(s));
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。