gpt4 book ai didi

java - 当我尝试将 json 数据发布到 Web 服务时,Android 应用程序崩溃

转载 作者:行者123 更新时间:2023-12-01 12:39:58 25 4
gpt4 key购买 nike

大家好,我正在尝试将数据从我的 Android 应用程序发送到 json 对象中的 Web 服务,但是当我单击发送按钮时应用程序崩溃了,有人可以帮助我解决我的问题吗?谢谢,下面是我的主要java代码:

public  class MainActivity extends Activity  {

private Button send;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

send= (Button)findViewById(R.id.btnSend);
send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("name", "toto");
jsonobj.put("twitter", "twito");
jsonobj.put("country", "totoland");
} catch (JSONException ex) {
//buildref.setText("Error Occurred while building JSON");
ex.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost("bbqhmkcode.appspot.com/jsonservlet");
StringEntity se = null;
try {
se = new StringEntity(jsonobj.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);
try {
HttpResponse httpresponse = httpclient.execute(httppostreq);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

这是 LogCat:

    08-08 15:11:51.790: I/Process(24024): Sending signal. PID: 24024 SIG: 9
08-08 15:12:34.440: W/dalvikvm(24321): threadid=11: thread exiting with uncaught exception (group=0x41d3e700)
08-08 15:12:34.510: E/AndroidRuntime(24321): FATAL EXCEPTION: AsyncTask #1
08-08 15:12:34.510: E/AndroidRuntime(24321): java.lang.RuntimeException: An error occured while executing doInBackground()
08-08 15:12:34.510: E/AndroidRuntime(24321): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-08 15:12:34.510: E/AndroidRuntime(24321): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-08 15:12:34.510: E/AndroidRuntime(24321): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-08 15:12:34.510: E/AndroidRuntime(24321): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-08 15:12:34.510: E/AndroidRuntime(24321): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-08 15:12:34.510: E/AndroidRuntime(24321): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-08 15:12:34.510: E/AndroidRuntime(24321): at java.lang.Thread.run(Thread.java:841)
08-08 15:12:34.510: E/AndroidRuntime(24321): Caused by: java.lang.NullPointerException
08-08 15:12:34.510: E/AndroidRuntime(24321): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:518)
08-08 15:12:34.510: E/AndroidRuntime(24321): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)

08-08 15:12:34.510: E/AndroidRuntime(24321): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 08-08 15:12:34.510:E/AndroidRuntime(24321):在com.example.MainActivity $ HttpAsyncTask.doInBackground(MainActivity.java:72) 08-08 15:12:34.510:E/AndroidRuntime(24321):在com.example.MainActivity $ HttpAsyncTask.doInBackground(MainActivity.java:1) 08-08 15:12:34.510: E/AndroidRuntime(24321): 在 android.os.AsyncTask$2.call(AsyncTask.java:287) 08-08 15:12:34.510: E/AndroidRuntime(24321): 在 java.util.concurrent.FutureTask.run(FutureTask.java:234)

最佳答案

您正在从主 UI 线程发送数据。尝试使用 AsyncTask<> 发送数据像这样

public  class MainActivity extends Activity  {

private Button send;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);



send= (Button)findViewById(R.id.btnSend);
send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// execute like this way
new HttpAsyncTask().execute("bbqhmkcode.appspot.com/jsonservlet");


});
}


private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {

JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("name", "toto");
jsonobj.put("twitter", "twito");
jsonobj.put("country", "totoland");
} catch (JSONException ex) {
//buildref.setText("Error Occurred while building JSON");
ex.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost();
StringEntity se = null;
try {
se = new StringEntity(jsonobj.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);

HttpResponse httpresponse = httpclient.execute(httppostreq);
InputStream inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";

return result;
}

private String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub

BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;

return result;

}

}


}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
//you will get result here in "result"
}
}

}

我已经编辑了您的代码,但您可能需要更正其格式这就是我的使用方式

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {



return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {

// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();

// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);

String json = "";

// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "jaimin");
jsonObject.accumulate("country","ind");
jsonObject.accumulate("twitter", "yoooo");

// 4. convert JSONObject to JSON to String
json = jsonObject.toString();



// 5. set json to StringEntity
StringEntity se = new StringEntity(json);

// 6. set httpPost Entity
httpPost.setEntity(se);

// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);

// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";

} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;

}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub

BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;

inputStream.close();
return result;

}
public boolean isConnected() {
// TODO Auto-generated method stub
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}

关于java - 当我尝试将 json 数据发布到 Web 服务时,Android 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25202481/

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