我试图通过POST方法将参数发送到php到mysql。我的代码似乎没有将参数加载到httpPost中。调试时,我看到httpPost变量下的参数为null,并且似乎没有拾取实体。如果您有任何帮助,我们将不胜感激。我正在使用android studio。
主要活动
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setSave(View view) {
new TestSQL().execute();
}
private class TestSQL extends AsyncTask<String, String, JSONObject> {
@Override
protected JSONObject doInBackground(String... params) {
WriteToDatabase write = new WriteToDatabase();
String a = "1";
String b = "2";
String c = "3";
String d = "4";
String e = "5";
String f = "6";
String g = "7";
JSONObject json1 = write.writeDB(a, b,
c, d, e, f, g);
return json1;
}
}
写数据库。java构建列表Namevaluepairs
public class WriteToDatabase {
private JSONParser test;
// URL of the PHP API
private static String link = "http://192.168.1.102/test/test2.php";
public JSONObject writeDB(String a,String b,
String c, String d,String e,String f,String g) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", b));
params.add(new BasicNameValuePair("description",
c));
params.add(new BasicNameValuePair("add", d));
params.add(new BasicNameValuePair("city", e));
params.add(new BasicNameValuePair("cat", a));
params.add(new BasicNameValuePair("uid", f));
params.add(new BasicNameValuePair("day", g));
JSONParser test = new JSONParser();
JSONObject json = test.getJSONFromUrl(link, params);
return json;
}
}
我的JSONParser。
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// With or without HTTP.UTF_8 won't work
DefaultHttpClient httpClient = new DefaultHttpClient();
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httpPost.setEntity(ent);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(httpEntity));
}
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();
json = sb.toString();
Log.e("JSON", 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;
}
}
还有我的Logcat
11-15 21:30:04.273 818-836/com.example.julian.testforsql E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalStateException: Content has been consumed
at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:100)
at com.example.julian.testforsql.JSONParser.getJSONFromUrl(JSONParser.java:57)
at com.example.julian.testforsql.WriteToDatabase.writeDB(WriteToDatabase.java:30)
at com.example.julian.testforsql.MainActivity$TestSQL.doInBackground(MainActivity.java:62)
at com.example.julian.testforsql.MainActivity$TestSQL.doInBackground(MainActivity.java:50)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
出于某种原因,可能是从Eclipse迁移到AndroidStudio,或者我无法理解的其他原因,我无法通过实体将参数放入httpPost。我在这里找到了这个输入链接描述,并按照如何通过json对象发送它的步骤进行了操作,然后修改了我的php代码。最终结果是:
主要活动:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setSave(View view) {
new TestSQL().execute();
}
private class TestSQL extends AsyncTask<String, String, JSONObject> {
@Override
protected JSONObject doInBackground(String... params) {
WriteToDatabase write = new WriteToDatabase();
String a = "1";
String b = "2";
String c = "3";
String d = "4";
String e = "5";
String f = "6";
String g = "7";
JSONObject json1 = null;
try {
json1 = write.writeDB(a, b,
c, d, e, f, g);
} catch (JSONException e1) {
e1.printStackTrace();
}
return json1;
}
}
}
写odatabase.class好像建筑参数
public class WriteToDatabase {
// URL of the PHP API
private static String link = "http://192.168.1.102/test/test.php";
public JSONObject writeDB(String a,String b,
String c, String d,String e,String f,String g) throws JSONException{
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", b);
jsonObj.put("description",c);
jsonObj.put("add", d);
jsonObj.put("city", e);
jsonObj.put("cat", a);
jsonObj.put("uid", f);
jsonObj.put("day", g);
JSONArray postjson=new JSONArray();
postjson.put(jsonObj);
JSONParser test = new JSONParser();
JSONObject json = test.getJSONFromUrl(link, postjson,jsonObj);
return json;
}
}
JSONparser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, JSONArray postjson, JSONObject json) {
// Making HTTP request
try {
HttpPost httpPost = new HttpPost(url);
// Post the data:
httpPost.setHeader("json", json.toString());
httpPost.getParams().setParameter("jsonpost", postjson);
// Execute HTTP Post Request
System.out.print(json);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
// for JSON:
if (response != null) {
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
并修改了我的php代码。我以前读过POST变量,但现在如何重新分配它们,我将此代码放在php的顶部,然后向mysql提供insert语句:
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
/回显“-------------\n”;
$_POST ['name'] = $data->name;
$_POST ['description']= $data->description;
$_POST ['add']= $data->add;
$_POST ['city']= $data->city;
$_POST ['uid']= $data->uid;
$_POST ['day']= $data->day;
$_POST ['cat']= $data->cat;
希望这对某人有帮助。
删除此行:
if (httpEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(httpEntity));
}
我刚刚发现调用EntityUtils。toString(httpEntity))
被计算为使用已使用(已消费)的实体
,因此得到异常
。
我从@dvm对这个问题的回答中知道了这一点(感谢他):
IllegalStateException:内容已被使用
问题内容: 我正在使用JDK 1.6.0_26中的VisualVM来分析在Tomcat下运行的Java Webapp,但是VisualVM经常告诉我它没有足够的内存来拍摄快照,并使用-Xmx开关为Netbeans提供更多的内存。 。问题是,我在Netbeans之外运行VisualVM,那么如何为jvisualvm.exe提供JVM参数? 问题答案: 应该能够修改内存中的设置 并且在排队。
我有以下供应商: 我需要创建这个提供程序的两个实例,一个将绑定一个用“默认”注释的网络资源注入,另一个将绑定一个用“其他”注释的网络资源注入。 让Guice创建提供程序实例如下: 如果我尝试手动实例化实例并提供自定义参数,那么注入的参数当然有问题。如果我遵循辅助符号,问题是我需要在模块中注入供应商的工厂,当然,这是完全关闭的! 有人能帮忙吗?
标准中似乎没有规则提到模板参数需要默认参数的情况。 在dcl中。fct。默认值#1 如果在参数声明中指定了初始化子句,则将此初始化子句用作默认参数。缺省参数将用于缺少尾随参数的调用。 在本节中,规则明确描述了何时为函数调用提供默认参数。但是,我在标准中没有找到与上面描述何时提供默认参数作为模板参数的语句类似的引用。 例如
如何在邮递员中传递此表单数据? 我试过这种方法,但不起作用
问题内容: 我正在通过此方法使用RESTfull Web服务: 在我的Android应用中,我想调用此方法。如何使用org.apache.http.client.methods.HttpPost给参数赋予正确的值; 我注意到我可以使用批注@HeaderParam并将标题添加到HttpPost对象。这是正确的方法吗?这样做: 在httpPost上使用setEntity方法将不起作用。它仅使用json
问题内容: 我必须通过Volley Framework提出要求。这是带有JSONObject的POST请求。 我必须传递一个字符串和一个JSONArray ..但是我怎么能呢? 我从这个开始: 如果我尝试使用浏览器,则必须进行以下设置: 问题答案: 您需要先制作一个JSON数组,然后将其存储