开发我的第一个基本的Android应用程序,下面是我打开连接的方式,它运行良好。
URL url = new URL("http://www.mocky.io/v2/568e3d730f0000da3fd1831b");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
现在,如何在此连接上发送数据或json对象?这只是打开一个连接,来验证?验证码是在打开连接之前还是如何工作?
感谢。
此致
答案 0 :(得分:0)
如果您要以Api Get
发送数据String loginUrl = getString(R.string.loginapi) + "emailid=" + emailIdEditText.getText().toString().trim() + "&password=" + passwordEditText.getText().toString().trim();
sendGet(loginUrl); //TODO:Use Async Task to execute these kind of operations
// HTTP GET request
public String sendGet(String apiUrl) {
StringBuilder result = new StringBuilder();
HttpURLConnection urlConnection = null;
try {
URL url = new URL(apiUrl);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
如果要将JSON字符串发送到URL,请按照步骤操作 创建模型,为对象赋值。 使用GSON库将对象转换为字符串(推荐)
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
String regString = gson.toJson(--Object--);
String createTeamURL = getString(R.string.createTeamapi);