[英]How to use post method in android using json
我已經創建了一個使用json從ro網站獲取並在listview中顯示的android應用,現在我想從我們的應用中添加數據,它也必須在我們應用的listview中顯示,然后它也必須在網站中顯示。如何使用發布方法並在我們的應用中顯示。
得到我那樣使用的方法
public class MainActivity extends ListActivity implements FetchDataListener
{
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_list_item);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://floating-wildwood-1154.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
@Override
public void onFetchComplete(List<Application> data)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
@Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
fetchdatatask.java
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
@Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
@Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* @param is
* respons string
* @return json string
* @throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
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 )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
像這樣我也使用get方法並顯示,出於相同的目的,我想將post方法添加到android listview中顯示並顯示在網站中。
如果我單擊菜單按鈕(如添加)將創建一個按鈕,則該按鈕將顯示一頁,在該頁面中,我必須添加數據並單擊保存,它也必須顯示在列表視圖中並在網站中發布
我該怎么做。
您可以使用HttpPost
@Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
try{
StringEntity s = new StringEntity(json.toString()); //json is ur json object
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
request.setEntity(s);
request.addHeader("Accept", "text/plain"); //give here your post method return type
HttpResponse response = client.execute(request);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
您必須采取的主要步驟是:
在您的Android應用中添加代碼以將數據發布到您的服務器。
您可以找到許多有關如何在線執行此操作的示例。 這是一個示例: 如何使用HTTPClient以JSON發送POST請求?
有一個可以處理您發送的JSON數據的Web服務。
如何執行此操作取決於您使用的服務器端技術。
更新與您的ListView綁定的列表
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://abcd.wxyz.com/");
try {
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IDToken1", "username"));
nameValuePairs.add(new BasicNameValuePair("IDToken2", "password"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if(response != null) {
int statuscode = response.getStatusLine().getStatusCode();
if(statuscode==HttpStatus.SC_OK) {
String strResponse = EntityUtils.toString(response.getEntity());
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.