HttpClient模块的HttpGet和HttpPost及Connection to refuse解决

无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。

1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

2.使用DefaultHttpClient类的execute方法发送HTTPGET或HTTPPOST请求,并返回HttpResponse对象。

3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。、

HttpGet方法public String doGet() {String uriAPI = "?name=jason&password=1234";String result= ""; // 创建HttpGet对象,将要请求的URL通过构造方法传入,参数附在url的后面。HttpGet httpRequst = new HttpGet(uriAPI);try { //使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);//其中HttpGet是HttpUriRequst的子类if(httpResponse.getStatusLine().getStatusCode() == 200){HttpEntity httpEntity = httpResponse.getEntity();result = EntityUtils.toString(httpEntity);//取出应答字符串}elsehttpRequst.abort();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return result; }

HttpPost方法

如果使用HttpPost方法提交HTTPPOST请求,则需要使用HttpPost类的setEntity方法设置请求参数。参数则必须用NameValuePair[]数组存储。

public String doPost() {String uriAPI = "";//Post方式没有参数在这里String result = "";HttpPost httpRequst = new HttpPost(uriAPI);//创建HttpPost对象List <NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("username", "jason"));params.add(new BasicNameValuePair("password", "1234"));try {httpRequst.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);if(httpResponse.getStatusLine().getStatusCode() == 200){HttpEntity httpEntity = httpResponse.getEntity();result = EntityUtils.toString(httpEntity);//取出应答字符串}}catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();result = e.getMessage().toString();}return result; }

实例:用HttpPost方法与php进行登陆交互

原理:android客户端通过HttpPost发送用户名和密码到服务器端,服务器端收到数据,连接到数据库查询,如果匹配正确,就输出login succeed返回给客户端

服务器端:

在mysql中新件testConnect数据库,创建users表

新建php项目,建立文件login.php<?php$dbhost="localhost:3306";//数据库的地址:端口号$dbuser="root";//用户名$dbpass="root";//密码$dbname="testConnect";//数据库名称$cn=mysql_connect($dbhost,$dbuser,$dbpass) or die("connect error");@mysql_select_db($dbname) or die("db error");mysql_query("set name 'UTF-8'");$username=$_POST['username'];$sql="select * from users where username='$username'";$query=mysql_query($sql);$rs=mysql_fetch_array($query);if(is_array($rs)){if($_POST['pwd']==$rs['password']){echo "login succeed";}else{echo "login error";}}?>客户端:

登陆界面布局

MainActivity.java代码:

package com.example.foodie;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v7.app.ActionBarActivity;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;public class MainActivity extends ActionBarActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.fragment_main);Button loginButton = (Button)findViewById(R.id.login);loginButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubEditText usernameText = (EditText)findViewById(R.id.username),passwordText = (EditText)findViewById(R.id.password);LoginHandle loginHandle =new LoginHandle(usernameText,passwordText);Thread loginThread = new Thread(loginHandle);loginThread.start();}});}}class LoginHandle implements Runnable{EditText usernameText,passwordText;public LoginHandle(EditText username,EditText password){this.usernameText = username;this.passwordText = password;}@Overridepublic void run(){String username = usernameText.getText().toString(),password = passwordText.getText().toString();//连接到服务器的地址String connectURL = "";//填入用户名密码和连接地址String result = "";//发送post请求HttpPost httpPost = new HttpPost(connectURL);//Post运作传送变数必须用NameValuePair[]阵列存储List<BasicNameValuePair>params = new ArrayList<BasicNameValuePair>();params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("pwd", password));//发出Http请求try{httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));//取回Http应答DefaultHttpClient client = new DefaultHttpClient();HttpResponse httpResponse = client.execute(httpPost);//若状态码为200则请求成功,取得返回的数据if(httpResponse.getStatusLine().getStatusCode() == 200){//取出字符串result = EntityUtils.toString(httpResponse.getEntity());}}catch(Exception e){e.printStackTrace();}if(result.equals("login succeed")){System.out.println("登陆成功,可以回家睡觉了少年!");}else {System.out.println("你是猪吗?");}}}关于org.apache.http.conn.HttpHostConnectException: Connection to refused错误的解决办法

不是每个人都一定快乐,不是每种痛都一定要述说。

HttpClient模块的HttpGet和HttpPost及Connection to refuse解决

相关文章:

你感兴趣的文章:

标签云: