【www.bbyears.com--.Net开发】
android开发想接口获取数据是必须的操作,一般获取数据有post和get两种方式,本文讲解客户端使用post方法调取服务器端使用asp.net webapi开发接口数据。
1、访问接口类
package http;
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.net.URLEncoder;
import android.widget.Toast;
public class HttpUtils {
public static String getJsonContent(String urlPath,String data) {
String webServiceUrl="http://hayi.8888.com";
try {
URL url = new URL(webServiceUrl+urlPath);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(3000);
connection.setRequestMethod("POST");
connection.setDoOutput(true); // 发送POST请求必须设置允许输出
connection.setDoInput(true);
//获取输出流
OutputStream os = connection.getOutputStream();
os.write(data.getBytes());
os.flush();
int code = connection.getResponseCode();
if (code == 200) {
return changeInputStream(connection.getInputStream());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "";
}
private static String changeInputStream(InputStream inputStream) {
// TODO Auto-generated method stub
String JsonString = "";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = 0;
byte[] data = new byte[1024];
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
JsonString = new String(outputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return JsonString;
}
}
2、使用方法
// 传递的数据
String dataPare = "userName=" + URLEncoder.encode(usernameTxt.getText().toString().trim(), "UTF-8")
+ "&userPass=" + URLEncoder.encode(userpassTxt.getText().toString().trim(), "UTF-8");
jsonString = HttpUtils
.getJsonContent("/api/Values/PostUserLogin",dataPare );