【发布时间】:2018-01-17 08:17:09
【问题描述】:
我是 android 新手,现在正在学习它。我正在开发一个应用程序,我能够成功地从获取请求中获得响应。现在我想用一个参数执行一个 POST 请求,这是我迄今为止想出的:
public class BGTask extends AsyncTask<String, String, String > {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
String color = "null";
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
//I want to pass the id parameter
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
int status = parentObject.getInt("status");
if(status == 1) {
color = parentObject.getString("bgcolor");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return color;
}
}
变量颜色是十六进制代码,即#FF0089
【问题讨论】:
-
使用 loopj 或任何其他网络调用库而不是 AsynchTask :loopj.com/android-async-http
-
请看一下 android 的改造库:square.github.io/retrofit 它几乎可以调用任何 API,而且非常易于使用。
标签: android post connection http-post