gpt4 book ai didi

java - 应用程序在 HttpResponse 上崩溃 httpResponse = httpClient.execute(httpGet);

转载 作者:行者123 更新时间:2023-11-29 21:43:21 27 4
gpt4 key购买 nike

我在android studio工作。我花了很多时间搜索如何从 mysql 数据库检索特定行,但实际上每次我的应用程序在 HttpResponse httpResponse = httpClient.execute(httpGet); 中崩溃时我都无法执行此操作。

这是 JSONParser 类

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();

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}


} 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();
int aa=sb.toString().indexOf("{");
int zz=sb.indexOf("{",aa+1);
String sss,zzz;
sss=sb.substring(932);
zzz=sb.substring(zz);
//json = sb.toString();
json=zzz.toString();
} 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);
/*JSONArray jsonArray=new JSONArray(json);
jObj=jsonArray.getJSONObject(0);*/

} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

这就是 Activity

public class EditProductActivity extends Activity {

EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;

String pid;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// single product url
private static final String url_product_detials = "http://10.20.40.105/android_connect/get_product_details.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);


// getting product details from intent
Intent i = getIntent();

// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);

// Getting complete product details in background thread
new GetProductDetails().execute();

});



}

/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EditProductActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {

// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());

// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array

// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);

// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);

// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));

}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});

return null;
}


/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}

最后是我的 php cod

<?php

/*
* Following code will get single product details
* A product is identified by product id (pid)
*/

// array for JSON response

$response = array();
$response["success"] = 0;

// include db connect class

require_once __DIR__ . '/db_connect.php';

// connecting to db

$db = new DB_CONNECT();

// check for post data

if (isset($_GET["pid"])) {
$pid = $_GET['pid'];

// get a product from products table
$result = mysql_query("SELECT * FROM products WHERE pid like $pid");

if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {

$result = mysql_fetch_array($result);

$product = array();
$product["pid"] = $result["pid"];
$product["name"] = $result["name"];
$product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;

// user node
$response["product"] = array();

array_push($response["product"], $product);

// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";

// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";

// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

最佳答案

在 list 中声明互联网权限:

<uses-permission android:name="android.permission.INTERNET" /> 

关于java - 应用程序在 HttpResponse 上崩溃 httpResponse = httpClient.execute(httpGet);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com