我无法处理onpostexecute结果,因为doInBackground似乎返回了一个我应该转换为字符串才能显示的对象。
这是OnPostExecute响应的屏幕:
问题是如何获得JSON RESPONSE
public class PostTask extends AsyncTask<URL, String, String> {
String error = "";
boolean flag = false;
Context mContext = null;
public PostTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(URL... data) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://example.it");
HttpResponse response = null;
try {
//add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>( 1);
nameValuePairs.add(new BasicNameValuePair("username", "xxxxxxxxxx"));
nameValuePairs.add(new BasicNameValuePair("password", "xxxxxxxxxx"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute http post
response = httpclient.execute(httppost);
} catch (Exception e) {
Toast.makeText(mContext, e.getMessage(),Toast.LENGTH_LONG).show();
flag = true;
error = e.getMessage();
e.printStackTrace();
}
return response.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(flag){
Toast.makeText(mContext, "HttpHostConnectException Occured: "+error, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "DONE "+s, Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:1)
这是为我工作的:
public class PostTask extends AsyncTask<URL, String, String> {
String error = "";
boolean flag = false;
Context mContext = null;
public PostTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(URL... data) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://example.com/");
HttpResponse response = null;
try {
//add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>( 1);
nameValuePairs.add(new BasicNameValuePair("username", "xxxxxxx"));
nameValuePairs.add(new BasicNameValuePair("password", "xxxxx"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute http post
response = httpclient.execute(httppost);
} catch (Exception e) {
Toast.makeText(mContext, e.getMessage(),Toast.LENGTH_LONG).show();
flag = true;
error = e.getMessage();
e.printStackTrace();
}
try {
return convertHttpResponseToString(response);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (flag) {
Toast.makeText(mContext, "HttpHostConnectException Occured: " + error, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "DONE " + s.toString(), Toast.LENGTH_SHORT).show();
}
}
private String convertHttpResponseToString(HttpResponse response) throws IOException {
InputStream responseStream = response.getEntity().getContent();
Scanner scanner = new Scanner(responseStream, "UTF-8");
String responseString = scanner.useDelimiter("\\Z").next();
scanner.close();
return responseString;
}
}
答案 1 :(得分:0)
首先切换到HttpURLConnection
。
例如: -
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
然后尝试从InputStream中获取字符串。
以下是工作示例。
/**
* Http post request that returns String as result(eg:- plain String or JSON String)
* @param query is the request query
*@return String that could be a plain String or JSON
*/
public String connect_POST(final String query) throws IOException{
HttpURLConnection con = (HttpURLConnection) new URL(_URL).openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setAllowUserInteraction(false);
con.connect();
OutputStream output = con.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(output);
writer.write(query);
writer.flush();
output.close();
writer.close();
int responseCode = con.getResponseCode();
Log.e("Request _URL : ", "" + _URL);
Log.e("Request params : ", "" + query);
Log.e("Response Code : ", "" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String bufferString = response.toString();
Log.e("bufferString : ", "" + bufferString);
return bufferString;
}
答案 2 :(得分:0)
将返回的结果转换为JSONObject。
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(flag){
Toast.makeText(mContext, "HttpHostConnectException Occured: "+error, Toast.LENGTH_SHORT).show();
} else {
if (s != null)
{
if (!s.equalsIgnoreCase(""))
{
JSONObject jsonobject = new JSONObject(s);
// if its and array of data then convert it to json array
JSONArray jsonArray = jsonObject.getJSONArray("name of the arry you are getting for example: 'Data'");
}
}
Toast.makeText(mContext, "DONE "+s, Toast.LENGTH_SHORT).show();
}
}
}
答案 3 :(得分:0)
您正在使用String作为返回类型。请改用HttpResponse
1。extends AsyncTask<URL, String, HttpResponse>
2.更改返回类型
@Override
protected HttpResponse doInBackground(URL... data)
3.回复;
4.更改参数类型并从响应中获取JSON对象
@Override
protected void onPostExecute(HttpResponse s) {
super.onPostExecute(s);
if(flag){
Toast.makeText(mContext, "HttpHostConnectException Occured: "+error, Toast.LENGTH_SHORT).show();
} else {
JSONObject jsonObject;
JSONArray jsonArray = null;
if (s != null)
{
try {
jsonObject = new JSONObject(s.toString());
jsonArray = jsonObject.getJSONArray("name of the arry you are getting for example: 'Data'");
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
Toast.makeText(mContext, "DONE "+jsonArray, Toast.LENGTH_SHORT).show();
}
}
答案 4 :(得分:0)
尝试执行您的请求(Found it here)
// Execute HTTP Post Request
ResponseHandler<String> responseHandler=new BasicResponseHandler();
return httpclient.execute(httppost, responseHandler);
请求导致异常。