java 调用 C# webapi
最近项目需要 java调用 .net 的webapi。
对于get来说很简单,但是post方法遇到了些问题,最后也是曲线救国。
先看代码
```java
public static void main(String[] args) throws Exception {
//DoGet(String url)
String resultGet = DoGet("http://localhost:14248/api/Report/GetTest?parentid=40");
//DoPost(String url,List<NameValuePair> nvps)
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("parentid", "40"));
String resultPost = DoPost("http://localhost:14248/api/Report/PostTest",nvps);
//DoPost(String url, JSONObject template)
JSONObject template = new JSONObject();
template.put("data",data);
String json=HttpWebapi.DoPost(urlString,template);
//DoPost(String url, String json)
SysUser user=new SysUser();
user.setAccount(etAccount.getText().toString());
user.setPassword(etPwd.getText().toString());
ApiRequest<SysUser> request=new ApiRequest<>();
request.setData(user);
String data=JsonConvert.toJSON(request);
String json = HttpWebapi.DoPost(AppConfig.getUrl() + "api/user/login", data);
}
public static String DoGet(String url) throws Exception {
HttpGet httpGet = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(httpGet);
HttpEntity he = resp.getEntity();
String respContent = EntityUtils.toString(he, "UTF-8");
return respContent;
}
public static String DoPost(String url,List<NameValuePair> nvps) throws Exception {
HttpPost httpost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse resp = client.execute(httpost);
HttpEntity he = resp.getEntity();
String respContent = EntityUtils.toString(he, "UTF-8");
return respContent;
}
public static String DoPost(String url, JSONObject template)throws Exception{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.setEntity(new StringEntity(template.toString(),"utf-8"));
HttpResponse resp = httpClient.execute(httpPost);
String respContent = EntityUtils.toString(resp.getEntity(), "UTF-8");
return respContent;
}
public static String DoPost(String url, String json) throws Exception{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.setEntity(new StringEntity(json,"utf-8"));
HttpResponse resp = httpClient.execute(httpPost);
String respContent = EntityUtils.toString(resp.getEntity(), "UTF-8");
return respContent;
}