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