×

androidhttpclient lie

androidhttpclient(如何在Android开发中用HttpClient连接网络数据)

admin admin 发表于2022-09-07 02:11:26 浏览89 评论0

抢沙发发表评论

本文目录

如何在Android开发中用HttpClient连接网络数据


HttpClient网络访问
一、HttpClient网络访问:
(一)、简介:
1、Apache组织提供了HttpClient项目,可以实现网络访问。在Android中,成功集成了HttpClient,所以在Android中可以直接使用HttpClient访问网络。
2、与HttpURLConnection相比,HttpClient将前者中的输入、输出流操作,统一封装成HttpGet、HttpPost、HttpRequest类。
HttpClient:网络连接对象;
HttpGet:代表发送GET请求;
HttpPost:代表发送POST请求;
HttpResponse:代表处理服务器响应的对象。
HttpEntity对象:该对象中包含了服务器所有的返回内容。
3、使用步骤:(六部曲)【重点】
创建HttpClient对象:通过实例化DefaultHttpClient获得;
创建HttpGet或HttpPost对象:通过实例化 HttpGet或HttpPost 获得,而构造方法的参数是urlstring(即需要访问的网络url地址)。也可以通过调用setParams()方法来添加请求参数;
调用HttpClient对象的execute()方法,参数是刚才创建的 HttpGet或HttpPost对象 ,返回值是HttpResponse对象;
通过response对象中的getStatusLine()方法和getStatusCode()方法获取服务器响应状态是否是200。
调用 HttpResponse对象的getEntity()方法,返回HttpEntity对象。而该对象中包含了服务器所有的返回内容。
借助EntityUtils的toString()方法或toByteArray()对 HttpEntity对象进行处理,也可以通过IO流对 HttpEntity对象进行操作。
(二)、封装HttpClientHelper工具类:
public class HttpClientHelper {
public static HttpClient checkNetwork(String url) {
HttpClient Map《String , Object》
* @return byte
*/
public static byte doPostSubmit(String url, Map《String, Object》 params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost requestPost = new HttpPost(url);
List《BasicNameValuePair》 parameters = new ArrayList《BasicNameValuePair》();
try {
if (params != null) {
for (Map.Entry《String, Object》 entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
BasicNameValuePair nameValuePair = new BasicNameValuePair(
key, value);
parameters.add(nameValuePair);
}
}
requestPost
.setEntity(new UrlEncodedFormEntity(parameters, “utf-8“));
HttpResponse httpResponse = httpClient.execute(requestPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

如何使用androidhttpclient访问web服务


1.服务器认证(Server Authentication)
HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials)。登录信息保存在HttpState类的实例中,可以通过 setCredentials(String realm, Credentials cred)和getCredentials(String realm)来获取或设置。
HttpClient内建的自动认证,可以通过HttpMethod类的setDoAuthentication(boolean doAuthentication)方法关闭,而且这次关闭只影响HttpMethod当前的实例。
2.代理认证(proxy authentication)
除了登录信息需单独存放以外,代理认证与服务器认证几乎一致。用 setProxyCredentials(String realm, Credentials cred)和 getProxyCredentials(String realm)设、取登录信息。
3.认证方案(authentication schemes)
是HTTP中规定最早的也是最兼容的方案,遗憾的是也是最不安全的一个方案,因为它以明码传送用户名和密码。它要求一个UsernamePasswordCredentials实例,可以指定服务器端的访问空间或采用默认的登录信息。

Android HttpClient怎么报


HttpClient在Android 6.0之后被谷歌废弃取消使用了
HttpClient适合在2.3之前的版本,而HttpURLConnection一直在优化,更轻量,效果更好,适合3.0以后的版本
目前谷歌建议使用HttpURLConnection请求网络,或者使用OkHttp来请求网络
-androidhttpclient

android 如何使用httpclient实现登录和注册()


首先你需要写一个asp或者jsp的服务器,确定服务器的地址,并配置好,其次android客户端需要写一个连接类,请看下边的例子

public static String urlstr = “http://192.168.101.198:8888/login.ashx“;
public static String senddata(String data) {
try {
URL url = new URL(urlstr);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), “utf8“));
return bufferedReader.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ““;
}
该方法就是向服务器提交数据的
-lie

android的自带的httpClient 怎么上传文件


Android上传文件到服务端可以使用HttpConnection 上传文件,也可以使用Android封装好的HttpClient类。当仅仅上传文件可以直接使用

②《关于android Http访问,上传,用了三个方法 》
-androidhttpclient

android http-httpclient与HttpURLConnection有什么不同


最近在研究Volley框架的源码,发现它在HTTP请求的使用上比较有意思,在Android 2.3及以上版本,使用的是HttpURLConnection,而在Android 2.2及以下版本,使用的是HttpClient。我也比较好奇这么使用的原因,于是专门找到了一位Google的工程师写的一篇博客,文中对HttpURLConnection和HttpClient进行了对比,下面我就给大家简要地翻译一下。
原文地址:
-lie

android里面可以使用HttpClient么


Android有一个AndroidHttpClient,实现了HttpClient接口,但是已经标记为Deprecated,不鼓励使用了。因为Android鼓励开发者使用HttpURLConnection这一套(在java.net包名下)。在Android blog官网上有专门说过原因,感兴趣你可以搜一下。基本意思就是HttpURLConnection在Android下针对手机环境做过一些优化,而AndroidHttpClient已经不再维护。
-androidhttpclient

android httpclient 怎么提交订单和订单明细参数


package cn.itcast.net;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.xmlpull.v1.XmlPullParser;
import android.util.Xml;
import cn.itcast.utils.StreamTool;
public class HttpRequest {
public static boolean sendXML(String path, String xml)throws Exception{
byte data = xml.getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(“POST“);
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
conn.setRequestProperty(“Content-Type“, “text/xml; charset=UTF-8“);
conn.setRequestProperty(“Content-Length“, String.valueOf(data.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200){
return true;
}
return false;
}
public static boolean sendGetRequest(String path, Map《String, String》 params, String enc) throws Exception{
StringBuilder sb = new StringBuilder(path);
sb.append(’?’);
// ?method=save&title=435435435&timelength=89&
for(Map.Entry《String, String》 entry : params.entrySet()){
sb.append(entry.getKey()).append(’=’)
.append(URLEncoder.encode(entry.getValue(), enc)).append(’&’);
}
sb.deleteCharAt(sb.length()-1);

URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(“GET“);
conn.setConnectTimeout(5 * 1000);
if(conn.getResponseCode()==200){
return true;
}
return false;
}

public static boolean sendPostRequest(String path, Map《String, String》 params, String enc) throws Exception{
// title=dsfdsf&timelength=23&method=save
StringBuilder sb = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry《String, String》 entry : params.entrySet()){
sb.append(entry.getKey()).append(’=’)
.append(URLEncoder.encode(entry.getValue(), enc)).append(’&’);
}
sb.deleteCharAt(sb.length()-1);
}
byte entitydata = sb.toString().getBytes();//得到实体的二进制数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(“POST“);
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
//Content-Type: application/x-www-form-urlencoded
//Content-Length: 38
conn.setRequestProperty(“Content-Type“, “application/x-www-form-urlencoded“);
conn.setRequestProperty(“Content-Length“, String.valueOf(entitydata.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200){
return true;
}
return false;
}

//SSL HTTPS Cookie
public static boolean sendRequestFromHttpClient(String path, Map《String, String》 params, String enc) throws Exception{
List《NameValuePair》 paramPairs = new ArrayList《NameValuePair》();
if(params!=null && !params.isEmpty()){
for(Map.Entry《String, String》 entry : params.entrySet()){
paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);//得到经过编码过后的实体数据
HttpPost post = new HttpPost(path); //form
post.setEntity(entitydata);
DefaultHttpClient client = new DefaultHttpClient(); //浏览器
HttpResponse response = client.execute(post);//执行请求
if(response.getStatusLine().getStatusCode()==200){
return true;
}
return false;
}
}
package cn.itcast.uploaddata;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import cn.itcast.net.HttpRequest;
import android.test.AndroidTestCase;
import android.util.Log;
public class HttpRequestTest extends AndroidTestCase {
private static final String TAG = “HttpRequestTest“;

public void testSendXMLRequest() throws Throwable{
String xml = “《?xml version=\“1.0\“ encoding=\“UTF-8\“?》《persons》《person id=\“23\“》《name》liming《/name》《age》30《/age》《/person》《/persons》“;
HttpRequest.sendXML(“http://192.168.1.100:8080/videoweb/video/manage.do?method=getXML“, xml);
}
public void testSendGetRequest() throws Throwable{
//?method=save&title=xxxx&timelength=90
Map《String, String》 params = new HashMap《String, String》();
params.put(“method“, “save“);
params.put(“title“, “liming“);
params.put(“timelength“, “80“);

HttpRequest.sendGetRequest(“http://192.168.1.100:8080/videoweb/video/manage.do“, params, “UTF-8“);
}

public void testSendPostRequest() throws Throwable{
Map《String, String》 params = new HashMap《String, String》();
params.put(“method“, “save“);
params.put(“title“, “中国“);
params.put(“timelength“, “80“);

HttpRequest.sendPostRequest(“http://192.168.1.100:8080/videoweb/video/manage.do“, params, “UTF-8“);
}

public void testSendRequestFromHttpClient() throws Throwable{
Map《String, String》 params = new HashMap《String, String》();
params.put(“method“, “save“);
params.put(“title“, “传智播客“);
params.put(“timelength“, “80“);

boolean result = HttpRequest.sendRequestFromHttpClient(“http://192.168.1.100:8080/videoweb/video/manage.do“, params, “UTF-8“);
Log.i(“HttRequestTest“, ““+ result);
}
}
服务器端代码:
package cn.itcast.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import cn.itcast.formbean.VideoForm;
import cn.itcast.utils.StreamTool;
public class VideoManageAction extends DispatchAction {

public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
VideoForm formbean = (VideoForm)form;
if(“GET“.equals(request.getMethod())){
byte data = request.getParameter(“title“).getBytes(“ISO-8859-1“);
String title = new String(data, “UTF-8“);
System.out.println(“title:“+ title);
System.out.println(“timelength:“+ formbean.getTimelength());
}else{
System.out.println(“title:“+ formbean.getTitle());
System.out.println(“timelength:“+ formbean.getTimelength());
}
//下面完成视频文件的保存
if(formbean.getVideo()!=null && formbean.getVideo().getFileSize()》0){
String realpath = request.getSession().getServletContext().getRealPath(“/video“);
System.out.println(realpath);
File dir = new File(realpath);
if(!dir.exists()) dir.mkdirs();
File videoFile = new File(dir, formbean.getVideo().getFileName());
FileOutputStream outStream = new FileOutputStream(videoFile);
outStream.write(formbean.getVideo().getFileData());
outStream.close();
}
return mapping.findForward(“result“);
}

public ActionForward getXML(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
InputStream inStream = request.getInputStream();
byte data = StreamTool.readInputStream(inStream);
String xml = new String(data, “UTF-8“);
System.out.println(xml);
return mapping.findForward(“result“);
}
}
-lie