码上敲享录 > android开发实例 > android如何调用后台接口

android如何调用后台接口

上一章章节目录下一章 2018-04-11已有4951人阅读 评论(0)

android如何调用后台接口?

解决方法:

1.android端请求代码:

//后端请求地址

String url="http://192.168.0.104:8080/PFMMIS/app/company/list.do";

//参数字符串,json字符串格式

String entity="{'name':'老王'}";


HttpClient httpClient = null;

HttpPost httpPost = new HttpPost(url);

try {

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

      trustStore.load(null, null);

      SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);

      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpParams params = new BasicHttpParams();

      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

      SchemeRegistry registry = new SchemeRegistry();

      registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

      registry.register(new Scheme("https", sf, 443));

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

      httpClient= new DefaultHttpClient(ccm, params);

httpPost.setEntity(new StringEntity(entity));

httpPost.setHeader("Accept", "application/json");

httpPost.setHeader("Content-type", "application/json");

HttpResponse resp = httpClient.execute(httpPost);

if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {

Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());

return null;

}

String result=EntityUtils.toString(resp.getEntity());//结果


2.后台接口代码:

@RequestMapping(value="/list")

@ResponseBody

public Map list(HttpServletRequest request) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));//post方式传递读取字符流

String jsonStr = null;

StringBuilder result = new StringBuilder();

try {

while ((jsonStr = reader.readLine()) != null) {

result.append(jsonStr);//获取字符串转json即可获取参数

}

} catch (IOException e) {

e.printStackTrace();

}

reader.close();// 关闭输入流

}

本文地址:http://www.yayihouse.com/yayishuwu/chapter/1171

243

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交