我正在尝试创建第一个使用REST API的android应用程序。我的api是用Node.JS编写的,并且已经使用Postman进行了测试,但是,我无法将JSON数据发送到我的api。
@Override
protected String doInBackground(String... params) {
String data = "";
String urlName = params[0];
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
我总是到达声明并初始化DataOutputSteam的行,并且不执行代码。我什至没有收到有关我的虚拟设备已经访问过我的服务器的日志。
我已经在清单XML中包含了这两个。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
答案 0 :(得分:0)
根据您的日志,您遇到了NetworkOnMainThreadException
,这阻止了网络请求的执行(取而代之的是进入您的catch
块)。这表明您没有正确调用AsyncTask-确保您正在调用execute
而不是doInBackground
。另请参阅here,以获取有关此常规模式的更多信息。
答案 1 :(得分:0)
尝试一下,这是用于POST方法的,它接受2个参数的电子邮件和密码。 根据您的要求进行更改
URL url = new URL(Login_url);
HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept" , "application/json");
conn.connect();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", "Your_Email")
.appendQueryParameter("password","Your_Password");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
code = conn.getResponseCode();
Log.e("Result", code + "");
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.e("Result",result.toString());