失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Java模拟HTTP/POST方式请求接口

Java模拟HTTP/POST方式请求接口

时间:2024-01-12 10:30:01

相关推荐

Java模拟HTTP/POST方式请求接口

Java模拟HTTP/POST方式请求接口:

java模拟http/post方式请求接口方法主体:

public String sendPost(JSONObject json, String url){String result = "";HttpPost post = new HttpPost(url);try{CloseableHttpClient httpClient = HttpClients.createDefault();post.setHeader("Content-Type","application/json;charset=utf-8");post.addHeader("Authorization", "Basic YWRtaW46");StringEntity postingString = new StringEntity(json.toString(),"utf-8");post.setEntity(postingString);HttpResponse response = httpClient.execute(post);InputStream in = response.getEntity().getContent();BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}br.close();in.close();result = strber.toString();if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){result = "服务器异常";}} catch (Exception e){System.out.println("请求异常");throw new RuntimeException(e);} finally{post.abort();}return result;}

接口调用方法:

public String sendPostTest() {JSONObject jsonObject = new JSONObject();//添加参数,参数为JSON格式jsonObject.put("namecode", "zhouxf4110");String url = "http://localhost/***/userMassage/queryUserByList";//调用接口,返回字符串,返回值自行处理String str = sendPost(jsonObject, url);System.out.println(str);return str;}

pom文件配置:

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.10</version></dependency><!-- /artifact/org.apache.httpcomponents/httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version></dependency>

如果觉得《Java模拟HTTP/POST方式请求接口》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。