我的知识在android中非常有限我是newBi,有谁能告诉我如何获得JSON的响应和发布信息....如果您有建议,请编辑我的代码并插入一个评论,以便我可以确定我缺少的方法。 我无法分析一些发布的相关问题,我已经做了我的研究,但我无法完善它。如果我的代码错误或不完整,请纠正我。Android http POST回复
public void httpConnection(HashMap<String, String> postDataParams) {
HttpURLConnection httpcon;
String url = "(url here...)";
String result;
try {
httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Key", "Value");
httpcon.setRequestProperty("action", "get_scoop");
httpcon.setRequestMethod("POST");
httpcon.connect();
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.close();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI() {
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e) {
Log.e("TAG", e.getMessage());
return e.getMessage();
}
try {
resultToDisplay = IOUtils.toString(in, "UTF-8");
//to [convert][1] byte stream to a string
} catch (IOException e) {
e.printStackTrace();
}
return resultToDisplay;
}
@Override
protected void onPostExecute(String result) {
//Update the UI
}
}
首先看你的代码,我会建议你使用'retrofit'或'httpOk'的API – KOTIOS
@MyMasterPeice你能给我例子是什么? – koroku