1. 程式人生 > >Android與Asp.net webApi引數傳遞

Android與Asp.net webApi引數傳遞

參考:

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;
/**
 * 來源參考:
 * http://www.cnblogs.com/babycool/p/3922738.html
 */
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();
        }
      }
    }
  }
}


HttpClient:

package com.example.newapibean;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.example.shancc.utils.LogUtils;
/**
 * 來源參考:
 * http://www.cnblogs.com/babycool/p/3922738.html
 */
public class WebApiHttpClientTest {

  /**
   * Get無引數請求:
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

   */
  public static void getTest(){

    try {
      String url = "http://url/api/values";
      org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
      
      HttpGet httpGet = new HttpGet(url);
      HttpResponse execute = httpClient.execute(httpGet);
      int statusCode = execute.getStatusLine().getStatusCode();
      if(statusCode == HttpStatus.SC_OK){
        String string = EntityUtils.toString(execute.getEntity());
        LogUtils.d(string);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
  Get新增單個引數請求:
  注意:請求是key值和Get(string value)裡的值相同。
       [HttpGet]
       public string Get(string value)
       {
           return "dddd";
       }
  */
  public void getParamTest(){
    try {
    String url = "http://url/api/GetName?value=dabao";
    org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
    
    HttpGet httpGet = new HttpGet(url);
    
    HttpResponse execute = httpClient.execute(httpGet);
    int statusCode = execute.getStatusLine().getStatusCode();
    if(statusCode == HttpStatus.SC_OK){
      String string = EntityUtils.toString(execute.getEntity());
      LogUtils.d(string);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  
}
  
  /**
   *Post傳遞單個引數
       [HttpPost]
        public string Post([FromBody]string value)
        {
            return "dddd";
        }
   */
  public void postParamTest(){
    try {
      String url = "http://url/api/GetName";
//      String url = "http://url/api/values";
      HttpPost httpPost = new HttpPost(url);
      
      org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
      
      List<NameValuePair> parameters = new ArrayList<>();;
      parameters.add(new BasicNameValuePair("", "value"));
      HttpEntity entity = new UrlEncodedFormEntity(parameters , "UTF-8");
//      HttpEntity entity = new StringEntity("hello");
      httpPost.setEntity(entity);
      
      
      HttpResponse execute = httpClient.execute(httpPost);
      int statusCode = execute.getStatusLine().getStatusCode();
      if(statusCode == HttpStatus.SC_OK){
        String string = EntityUtils.toString(execute.getEntity());
        LogUtils.d(string);
      }
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
  
  /**
   Post傳遞多個引數
   伺服器需要使用一個Bean進行接收,屬性名稱需要一致
        [HttpPost]
        public string Post([FromBody]User value)
        {
            string userName = value.UserName;
            return value.UserName +","+value.Age;
        }
   */
  public void postParamsTwo(){

    try {
      String url = "http://url/api/GetName";
      HttpPost httpPost = new HttpPost(url);
      
      org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
      
      List<NameValuePair> parameters = new ArrayList<>();;
      parameters.add(new BasicNameValuePair("UserName", "dabao"));
      parameters.add(new BasicNameValuePair("Age", "21"));
      HttpEntity entity = new UrlEncodedFormEntity(parameters , "UTF-8");
      httpPost.setEntity(entity);
      
      
      HttpResponse execute = httpClient.execute(httpPost);
      int statusCode = execute.getStatusLine().getStatusCode();
      if(statusCode == HttpStatus.SC_OK){
        String string = EntityUtils.toString(execute.getEntity());
        LogUtils.d(string);
      }
      
    } catch (Exception e) {
      e.printStackTrace();
    }
  
  }
  
  
  /**
   Post提交多個引數:引數格式使用Json
   伺服器程式碼:
        [HttpPost]
        public string Post([FromBody]User value)
        {
            string userName = value.UserName;
            return value.UserName +","+value.Age;
        }   
   */
  public void postParamsJson(){

    try {
      String url = "http://url/api/GetName";
      HttpPost httpPost = new HttpPost(url);
      org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
      
      List<NameValuePair> parameters = new ArrayList<>();;
      parameters.add(new BasicNameValuePair("UserName", "dabao"));
      parameters.add(new BasicNameValuePair("Age", "21"));
      JSONObject object = new JSONObject();
      object.put("UserName", "dabao");
      object.put("Age", "21");
      String paramsString = object.toJSONString();
      
      StringEntity entity = new StringEntity(paramsString);
      entity.setContentType("application/json");
      httpPost.setEntity(entity);
      
      HttpResponse execute = httpClient.execute(httpPost);
      int statusCode = execute.getStatusLine().getStatusCode();
      if(statusCode == HttpStatus.SC_OK){
        String string = EntityUtils.toString(execute.getEntity());
        LogUtils.d(string);
      }
      
    } catch (Exception e) {
      e.printStackTrace();
    }
    
  
  }
}