从服务器获取数据时,我经常遇到错误。从过去几周开始,这种情况正在发生。有时有效,有时无效。 logcat 显示错误在 jsonparser 文件中,而
httpclient.execute
但无法纠正,为什么?
exercise.java
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
// getting JSON string from URL
parametres.add(new BasicNameValuePair("inputChar", inputChar));
**JSONObject json = jsonParser.makeHttpRequest(url_display_user,
"GET", parametres);**
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
exercises = json.getJSONArray(TAG_RESPONSE);
// looping through All RESPONSE
for (int i = 0; i < exercises.length(); i++) {
JSONObject jsonobj = exercises.getJSONObject(i);
// Storing each json item in variable
String id = jsonobj.getString(TAG_ID);
String activityname = jsonobj.getString(TAG_ACTIVITY_NAME);
String metvalue = jsonobj.getString(TAG_METVALUE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_ACTIVITY_NAME, activityname);
map.put(TAG_METVALUE, metvalue);
// adding HashList to ArrayList
exerciseitems.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
jsonparser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println(is + "post");
}else if(method == "GET"){
System.out.println("1");
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
System.out.println("2");
String paramString = URLEncodedUtils.format(params, "utf-8");
System.out.println("3");
url += "?" + paramString;
System.out.println("4");
HttpGet httpGet = new HttpGet(url);
System.out.println("5");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("6");
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("7");
is = httpEntity.getContent();
System.out.println(is + "get");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("TagCovertS", "["+json+"]");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I get this error while fetching data
又一个错误
最佳答案
您可以使用 httpurlconnection,它启用了 SSL,并且比 httpclient 安全得多。
public class HttpPostData extends AsyncTask<String, Void, String>{
private String URL;
private JSONObject jsonObjSend;
int mResponseCode = -1;
private Object totaltime;
private long starttime;
public HttpPostData(String URL, JSONObject jsonObjSend) {
this.URL = URL;
this.jsonObjSend = jsonObjSend;
}
@Override
protected String doInBackground(String... params) {
String finalResult = null;
URL url = null;
HttpsURLConnection urlConnection = null;
try {
url=new URL(URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(500);
urlConnection.setReadTimeout(500);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonObjSend.toString());
out.close();
starttime = System.currentTimeMillis();
try {
mResponseCode = urlConnection.getResponseCode();
totaltime = System.currentTimeMillis() - starttime;
Log.e("HTTP POST Response Code:", ""
+ mResponseCode);
} catch (SSLPeerUnverifiedException e) {
Log.e("Exception", Log.getStackTraceString(e));
} catch (IOException e) {
Log.e("Exception", Log.getStackTraceString(e));
Log.e("HTTP POST Response Code(2):", ""
+ mResponseCode);
}
关于android - 应用程序在 httprequest 上频繁崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30183410/