Android Studio 调用 Asp.net 的 webApi Json参数传递

本文详细介绍了如何使用Android Studio通过HttpUrlConnection调用ASP.NET的WebAPI,包括GET和POST请求,单个及多个参数传递,以及JSON格式参数的处理。

Android Studio 调用 Asp.net 的 webApi Json参数传递

HttpUrlConnection:

package com.example.newapibean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import com.alibaba.fastjson.JSONObject;
import com.example.shancc.utils.LogUtils;
/**
 * 来源参考:
 * https://mp.csdn.net/mdeditor/100109135
 */
public class WebApiTest {

  /**
   * Get请求:没有参数
   * 
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
   */
  public static void httpConnGet() {

    String resultString = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    ByteArrayOutputStream bos = null;
    try {
      String srcUrl = "http://url/api/values";
      URL url = new URL(srcUrl );
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(10000);
      conn.setRequestMethod("GET");
      // 请求头必须设置,参数必须正确。
      conn.setRequestProperty("Accept", "application/json,text/html;q=0.9,image/webp,*/*;q=0.8");
      conn.setRequestProperty("Cache-Control", "max-age=0");
      conn.setDoInput(true);
      conn.setDoOutput(false);

      conn.connect();

      int responseCode = conn.getResponseCode();
      if (responseCode == 200 || true) {
        if (null != conn.getHeaderField("Content-Encoding")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else {
          inputStream = conn.getInputStream();
        }

        bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
          bos.write(buffer, 0, len);
        }
        bos.flush();
        byte[] resultByte = bos.toByteArray();
        LogUtils.d(resultByte.length + "");
        resultString = new String(resultByte);
      } else {
        LogUtils.e("httpUtils", "ResponseCode:" + responseCode);
      }
      LogUtils.d(resultString + "");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   Get添加单个参数请求:
   注意:请求是key值和Get(string value)里的值相同。
        [HttpGet]
        public string Get(string value)
        {
            string userName = value;
            HttpContent content = Request.Content;
            return "dddd";


        }
   */
  public void getParamTest(){

  String resultString = null;
  HttpURLConnection conn = null;
  InputStream inputStream = null;
  ByteArrayOutputStream bos = null;
  try {
    String srcUrl = "http://url/api/GetName" + "?value=dabao";
    URL url = new URL(srcUrl);
    conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(10000);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json,text/html;q=0.9,image/webp,*/*;q=0.8");
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setDoInput(true);
    conn.setDoOutput(false);
    conn.connect();

    int responseCode = conn.getResponseCode();
    if (responseCode == 200 || true) {
      if (null != conn.getHeaderField("Content-Encoding")) {
        inputStream = new GZIPInputStream(conn.getInputStream());
      } else {
        inputStream = conn.getInputStream();
      }

      bos = new ByteArrayOutputStream();
      byte[] buffer = new byte[10240];
      int len = -1;
      while ((len = inputStream.read(buffer)) != -1) {
        bos.write(buffer, 0, len);
      }
      bos.flush();
      byte[] resultByte = bos.toByteArray();
      LogUtils.d(resultByte.length + "");
      resultString = new String(resultByte);
    } else {
      LogUtils.e("httpUtils", "ResponseCode:" + responseCode);
    }
    LogUtils.d(resultString + "");
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (conn != null) {
      conn.disconnect();
    }
    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    if (bos != null) {
      try {
        bos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
  
  /**
   * 1.post无参数请求
   * 2.post单个参数请求
   */
  /**
           [HttpPost]
        public string Post([FromBody]string value)
        {
            return "dddd";
        }
         通过上面的测试我就也能够猜测到,Web API 要求请求传递的 [FromBody] 参数,肯定是有一个特定的格式,才能被正确的获取到。而这种特定的格式并不是我们常见的 key=value 的键值对形式。Web API 的模型绑定器希望找到 [FromBody] 里没有键名的值,也就是说, 不是 key=value ,而是 =value 。
   *
   */
  public void httpConnPostString() {

    String paramsString = "=" + "value";

    String resultString = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    ByteArrayOutputStream bos = null;
    try {
      String srcUrl = "http://url/api/GetName";
      URL url = new URL(srcUrl );
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(10000);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.connect();

      // 传入参数
      OutputStream outputStream = conn.getOutputStream();
      outputStream.write(paramsString.getBytes());


      int responseCode = conn.getResponseCode();
      if (responseCode == 200 || true) {
        if (null != conn.getHeaderField("Content-Encoding")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else {
          inputStream = conn.getInputStream();
        }

        bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
          bos.write(buffer, 0, len);
        }
        bos.flush();
        byte[] resultByte = bos.toByteArray();
        LogUtils.d(resultByte.length + "");
        resultString = new String(resultByte);
      } else {
        LogUtils.e("httpUtils", "ResponseCode:" + responseCode);
      }
      LogUtils.d(resultString + "");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  
  /**
  Post传递多个参数
  服务器需要使用一个Bean进行接收,属性名称需要一致
       [HttpPost]
       public string Post([FromBody]User value)
       {
           string userName = value.UserName;
           return value.UserName +","+value.Age;
       }
  */
  public void postParamsTest(){


    String resultString = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    ByteArrayOutputStream bos = null;
    try {
      String srcUrl = "http://url/api/GetName";
      URL url = new URL(srcUrl );
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(10000);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.connect();

      String paramsString = "UserName=dabao&Age=21";
      //传入参数
      OutputStream outputStream = conn.getOutputStream();
      outputStream.write(paramsString.getBytes());
      
      
      int responseCode = conn.getResponseCode();
      if (responseCode == 200 || true) {
        if (null != conn.getHeaderField("Content-Encoding")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else {
          inputStream = conn.getInputStream();
        }

        bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
          bos.write(buffer, 0, len);
        }
        bos.flush();
        byte[] resultByte = bos.toByteArray();
        LogUtils.d(resultByte.length + "");
        resultString = new String(resultByte);
      } else {
        LogUtils.e("httpUtils", "ResponseCode:" + responseCode);
      }
      LogUtils.d(resultString + "");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  
  
  /**
   Post提交多个参数:参数格式使用Json
   服务器代码:
        [HttpPost]
        public string Post([FromBody]User value)
        {
            string userName = value.UserName;
            return value.UserName +","+value.Age;
        }   
   */
  public void postParamsJson(){
    String resultString = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    ByteArrayOutputStream bos = null;
    try {
      String srcUrl = "http://url/api/GetName";
      URL url = new URL(srcUrl);
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(10000);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.connect();

      JSONObject object = new JSONObject();
      object.put("UserName", "dabao");
      object.put("Age", "21");
      String  paramsString = object.toJSONString();
      
      //传入参数
      OutputStream outputStream = conn.getOutputStream();
      outputStream.write(paramsString.getBytes());
      
      int responseCode = conn.getResponseCode();
      if (responseCode == 200 || true) {
        if (null != conn.getHeaderField("Content-Encoding")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else {
          inputStream = conn.getInputStream();
        }

        bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
          bos.write(buffer, 0, len);
        }
        bos.flush();
        byte[] resultByte = bos.toByteArray();
        LogUtils.d(resultByte.length + "");
        resultString = new String(resultByte);
      } else {
        LogUtils.e("httpUtils", "ResponseCode:" + responseCode);
      }
      LogUtils.d(resultString + "");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值