Post方式请求网络数据

来源:互联网 发布:怎样安装t3软件 编辑:程序博客网 时间:2024/06/06 03:35
<span style="font-size:18px;">第一个活动界面public class MainActivity extends Activity {String key = "3ac9f31ff66b9746539472887b3799c3";// 接口地址String path = "http://web.juhe.cn:8080/constellation/getAll";private EditText ed;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ed = (EditText) findViewById(R.id.editText1);tv = (TextView) findViewById(R.id.textView);}public void send(View v) {// 获取输入框的内容final String name = ed.getText().toString();if (!TextUtils.isEmpty(name)) {new Thread() {@Overridepublic void run() {httpPost(name);}}.start();} else {Toast.makeText(MainActivity.this, "请输入星座", 0).show();}}public void httpPost(String name) {HttpClient httpClient = new DefaultHttpClient();// 通过post方式请求HttpPost httpPost = new HttpPost(path);List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("consName", name));parameters.add(new BasicNameValuePair("type", "year"));parameters.add(new BasicNameValuePair("key", key));UrlEncodedFormEntity encodedFormEntity;try {// 设置实体内容和编码格式encodedFormEntity = new UrlEncodedFormEntity(parameters, "utf-8");// 设置实体,用于传递给服务器参数httpPost.setEntity(encodedFormEntity);// 请求网络HttpResponse httpResponse = httpClient.execute(httpPost);// 先得到状态行,从状态行里得到状态码if (httpResponse.getStatusLine().getStatusCode() == 200) {// 得到实体HttpEntity entity = httpResponse.getEntity();// 请求到的json// entity.getContent();final String string = EntityUtils.toString(entity);Gson gson = new Gson();gson.fromJson(string, Bean.class);runOnUiThread(new Runnable() {@Overridepublic void run() {tv.setText(string);}});}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}</span>



1 0