java访问controller示例

package  com.ocl.www.utils;

import  net.sf.json.JSONArray;
import  net.sf.json.JSONObject;
import  org.apache.http.NameValuePair;
import  org.apache.http.client.ClientProtocolException;
import  org.apache.http.client.entity.UrlEncodedFormEntity;
import  org.apache.http.client.methods.CloseableHttpResponse;
import  org.apache.http.client.methods.HttpGet;
import  org.apache.http.client.methods.HttpPost;
import  org.apache.http.impl.client.CloseableHttpClient;
import  org.apache.http.impl.client.HttpClients;
import  org.apache.http.message.BasicNameValuePair;
import  org.apache.http.util.EntityUtils;

import  java.io.BufferedReader;
import  java.io.IOException;
import  java.io.InputStreamReader;
import  java.io.OutputStream;
import  java.net.*;
import  java.util.ArrayList;
import  java.util.List;
import  java.util.Map;
import  java.util.Set;

/**
* Created by Administrator on 2016/12/16.
*/
public class  OutServerUntils {

//private static String targetURL = "http://192.168.1.39:8012/ocl-search-server/solrArticleController/queryDocsTest";
//private static final String targetURL = "http://192.168.1.39:8012/ocl-search-server/article/selectAllArticle";

/**
* 处理get请求.
@param  url  请求路径
@return  json
*/
public  String get(String url,String sendstr){
//实例化httpclient
CloseableHttpClient httpclient = HttpClients. createDefault ();
//实例化get方法
HttpGet httpget =  new  HttpGet(url);

try  {
httpget.setURI( new  URI(httpget.getURI().toString() +  "?"  + sendstr));
catch  (URISyntaxException e) {
e.printStackTrace();
}
//请求结果
CloseableHttpResponse response =  null ;
String content = "" ;
try  {
//执行get方法
response = httpclient.execute(httpget);
if (response.getStatusLine().getStatusCode()== 200 ){
content = EntityUtils. toString (response.getEntity(), "utf-8" );
System. out .println(content);
}
catch  (ClientProtocolException e) {
e.printStackTrace();
catch  (IOException e) {
e.printStackTrace();
}
return  content;
}


/**
* 处理post请求.
@param  url  请求路径
@param  params  参数
@return  json
*/
public  String post(String url,Map<String, String> params){
//实例化httpClient
CloseableHttpClient httpclient = HttpClients. createDefault ();
//实例化post方法
HttpPost httpPost =  new  HttpPost(url);
//处理参数
List<NameValuePair> nvps =  new  ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add( new  BasicNameValuePair(key, params.get(key)));
}
//结果
CloseableHttpResponse response =  null ;
String content= "" ;
try  {
//提交的参数
UrlEncodedFormEntity uefEntity =  new  UrlEncodedFormEntity(nvps,  "UTF-8" );
//将参数给post方法
httpPost.setEntity(uefEntity);
//执行post方法
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode()== 200 ){
content = EntityUtils. toString (response.getEntity(), "utf-8" );
System. out .println(content);
}
catch  (ClientProtocolException e) {
e.printStackTrace();
catch  (IOException e) {
e.printStackTrace();
}
return  content;
}



public static  String callInterface(String targetURL,String input,String requestMethod,String contentType){
String output =  null ;

try  {
URL targetUrl =  new  URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput( true );
httpConnection.setRequestMethod(requestMethod);
httpConnection.setRequestProperty( "Content-Type" , contentType);

//String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";
//String input = "{\"solrdata\":234}";
///String input = "{}";
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes( "utf-8" ));
outputStream.flush();

if  (httpConnection.getResponseCode() !=  200 ) {
throw new  RuntimeException( "Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}

BufferedReader responseBuffer =  new  BufferedReader( new  InputStreamReader((httpConnection.getInputStream())));

output = responseBuffer.readLine();
// System.out.println("Output from Server:\n");
//while ((output = responseBuffer.readLine()) != null) {
// System.out.println(output);
//}

httpConnection.disconnect();

catch  (MalformedURLException e) {

e.printStackTrace();

catch  (IOException e) {

e.printStackTrace();

}

return  output;
}

public static void  main(String[] args) {

// String targetURL = "http://192.168.1.39:8012/ocl-search-server/article/selectAllArticle";
// String input = "{}";

// String targetURL = "http://192.168.1.39:8012/ocl-search-server/solrArticleController/queryDocsTest";
// String input = "{\"solrdata\":234}";
//
// String data = OutServerUntils.callInterface(targetURL,input,"","application/x-www-form-urlencoded");
// System.out.println(JSONObject.fromObject(data).get("listarti"));
// System.out.println(JSONArray.fromObject(JSONObject.fromObject(data).get("listarti")).size());

// post请求方式
// OutServerUntils hd = new OutServerUntils();
// Map<String,String> map = new HashMap();
// map.put("appid","CALLBELL1");
// map.put("mtype","query");
// map.put("timestamp","timestamp");
// map.put("sign","73fadcd81c2970c0b602d026308266b7");
// map.put("params","{mobilePhone:15017573651}");
// hd.post("http://192.168.1.39/cas-server-webapp/api",map);

// get请求方式(参数写法有问题)
OutServerUntils hd =  new  OutServerUntils();
String sendstr =  "appid=CALLBELL1&mtype=query&timestamp=timestamp&sign=73fadcd81c2970c0b602d026308266b7&params={mobilePhone:15017573651}" ;
String content = hd.get( "http://192.168.1.39/cas-server-webapp/api" ,sendstr);
System. out .println(content); }
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是获取HTTP请求body的示例代码: ```java @PostMapping("/example") public String exampleController(@RequestBody String requestBody) { // 处理请求body return "处理完成"; } ``` 以上代码是在Spring框架下使用`@RequestBody`注解获取HTTP请求body的示例。 ### 回答2: 在JavaSpring框架中,可以通过以下代码示例controller层获取HTTP请求的body。 ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping("/example") public String handleRequest(@RequestBody String requestBody) { // requestBody 是HTTP请求的body内容 // 在这里可以根据需要对requestBody进行处理 // 返回处理后的结果 return "处理结果"; } } ``` 在上面的代码示例中,我们通过`@RequestBody`注解将接收到的HTTP请求的body映射到`requestBody`参数中。`requestBody`的类型可以是字符串,也可以是一个自定义的Java对象,具体根据实际需求进行选择。 在`handleRequest`方法中,可以对请求的body内容进行处理,例如解析JSON格式的数据,根据请求的参数进行业务逻辑处理等。最后,根据处理结果,可将结果返回,供客户端使用。 这样,我们就可以在Controller层获取HTTP请求的body内容,然后按照业务需求进行相应的处理。 ### 回答3: 在JavaController层中,我们可以使用Spring框架来获取HTTP请求的body。下面是一个简单的代码示例: ```java import org.springframework.http.HttpEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping("/example") public ResponseEntity<String> handleRequest(@RequestBody String requestBody) { // 处理请求的业务逻辑 System.out.println(requestBody); // 打印请求体内容 return ResponseEntity.ok("请求已成功处理"); } } ``` 在上述代码中,`@PostMapping("/example")`表示该Controller方法将处理一个HTTP的POST请求,并且请求路径为`/example`。`@RequestBody`注解表示将请求体的内容绑定到方法参数`requestBody`上,因此我们可以直接在方法中访问和处理请求体的内容。 通过打印`requestBody`,我们可以在控制台中看到请求体的内容。 值得注意的是,在实际开发过程中,我们通常会创建一个POJO对象来映射请求体的内容,而不仅仅是使用`String`类型来接收。这样可以更好地对请求体进行封装和处理。但是无论使用什么类型,原理都是相同的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值