Post方式请求网络数据
2016-05-14 11:50
435 查看
<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; @Override protected 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() { @Override public 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() { @Override public void run() { tv.setText(string); } }); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </span>
相关文章推荐
- 解决iOS9更新后http协议和https协议的问题
- Get方式请求网络数据+Fragment+SharedPreferences
- 图论(floyd算法):NOI2007 社交网络
- HttpClient4.3版本设置超时
- java发送http的get、post请求
- TCP进入快速恢复时的窗口下降算法
- http://www.2cto.com/database/201408/327315.html
- 网络请求
- Tomcat - 设置 HTTP 摘要认证
- 网络仿真NS2之——环境配置
- cf653d Delivery Bears【二分+网络流】
- tomcat 配置https 访
- 网络流二十四题之二十四 —— 骑士共存问题(KNI)
- IdHTTPServer1 收到POST 文件和参数
- http://nianjian.xiaze.com/tags.php?/%E5%BC%80%E5%B0%81%E5%B9%B4%E9%89%B4/1/13463189106/
- 网络流二十四题之九 —— 方格取数问题(GRID)
- 怎样使用HTTP协议访问网络
- 【bzoj4538】[Hnoi2016]网络
- 驱动安装失败在PC端ADB通过TCPIP连接调试
- Http请求状态码