首页 > 代码库 > HttpGet和HttpPost
HttpGet和HttpPost
1 package net.blogjava.mobile; 2 3 import java.net.HttpURLConnection; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 import org.apache.http.HttpResponse; 8 import org.apache.http.NameValuePair; 9 import org.apache.http.client.entity.UrlEncodedFormEntity;10 import org.apache.http.client.methods.HttpGet;11 import org.apache.http.client.methods.HttpPost;12 import org.apache.http.impl.client.DefaultHttpClient;13 import org.apache.http.message.BasicNameValuePair;14 import org.apache.http.protocol.HTTP;15 import org.apache.http.util.EntityUtils;16 17 import android.app.Activity;18 import android.os.Bundle;19 import android.view.View;20 import android.view.View.OnClickListener;21 import android.widget.Button;22 import android.widget.EditText;23 import android.widget.TextView;24 25 public class Main extends Activity implements OnClickListener26 {27 28 @Override29 public void onClick(View view)30 {31 String url = "http://169.254.103.188/querybooks/QueryServlet";32 TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);33 EditText etBookName = (EditText) findViewById(R.id.etBookName);34 HttpResponse httpResponse = null;35 try36 {37 38 switch (view.getId())39 {40 case R.id.btnGetQuery:41 url += "?bookname=" + etBookName.getText().toString();42 HttpGet httpGet = new HttpGet(url);43 httpResponse = new DefaultHttpClient().execute(httpGet);44 if (httpResponse.getStatusLine().getStatusCode() == 200)45 {46 47 String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);48 tvQueryResult.setText(result);49 System.out.println(result);50 }51 break;52 53 case R.id.btnPostQuery:54 HttpPost httpPost = new HttpPost(url);55 List<NameValuePair> params = new ArrayList<NameValuePair>();56 params.add(new BasicNameValuePair("bookname", etBookName57 .getText().toString()));58 httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));59 60 httpResponse = new DefaultHttpClient().execute(httpPost);61 if (httpResponse.getStatusLine().getStatusCode() == 200)62 {63 String result = EntityUtils.toString(httpResponse64 .getEntity());65 tvQueryResult.setText(result.replaceAll("\r", ""));66 }67 break;68 }69 }70 catch (Exception e)71 {72 tvQueryResult.setText(e.getMessage());73 }74 75 }76 77 @Override78 public void onCreate(Bundle savedInstanceState)79 {80 super.onCreate(savedInstanceState);81 setContentView(R.layout.main);82 Button btnGetQuery = (Button) findViewById(R.id.btnGetQuery);83 Button btnPostQuery = (Button) findViewById(R.id.btnPostQuery);84 btnGetQuery.setOnClickListener(this);85 btnPostQuery.setOnClickListener(this);86 87 }88 }
HttpGet和HttpPost
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。