Android HTTP请求方式

Posted qq^^614136809

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android HTTP请求方式相关的知识,希望对你有一定的参考价值。

1.HttpClient使用流程
基本流程:

2.HttpClient使用示例
1)使用HttpClient发送GET请求
直接贴下简单的发送Get请求的代码:

public class MainActivity extends Activity implements OnClickListener

private Button btnGet;
private WebView wView;
public static final int SHOW_DATA = 0X123;
private String detail = "";

private Handler handler = new Handler() 
    public void handleMessage(Message msg) 
        if(msg.what == SHOW_DATA)
        
            wView.loadDataWithBaseURL("",detail, "text/html","UTF-8","");
        
    ;
;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    setView();


private void initView() 
    btnGet = (Button) findViewById(R.id.btnGet);
    wView = (WebView) findViewById(R.id.wView);


private void setView() 
    btnGet.setOnClickListener(this);
    wView.getSettings().setDomStorageEnabled(true);

@Override
public void onClick(View v) 
    if (v.getId() == R.id.btnGet) 
        GetByHttpClient();
    

private void GetByHttpClient() 
    new Thread()
    
        public void run() 
        
                try 
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet("http://www.w3cschool.cc/python/python-tutorial.html");
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) 
                        HttpEntity entity = httpResponse.getEntity();
                        detail = EntityUtils.toString(entity, "utf-8");
                        handler.sendEmptyMessage(SHOW_DATA);
                    
                 catch (Exception e) 
                    e.printStackTrace();
                
        ;
    .start();


运行截图

另外,如果是带有参数的GET请求的话,我们可以将参数放到一个List集合中,再对参数进行URL编码, 最后和URL拼接下就好了:

List params = new LinkedList();
params.add(new BasicNameValuePair(“user”, “猪小弟”));
params.add(new BasicNameValuePair(“pawd”, “123”));
String param = URLEncodedUtils.format(params, “UTF-8”);
HttpGet httpGet = new HttpGet(“http://www.baidu.com”+“?”+param);
2)使用HttpClient发送POST请求
POST请求比GET稍微复杂一点,创建完HttpPost对象后,通过NameValuePair集合来存储等待提交 的参数,并将参数传递到UrlEncodedFormEntity中,最后调用setEntity(entity)完成, HttpClient.execute(HttpPost)即可;这里就不写例子了,暂时没找到Post的网站,又不想 自己写个Servlet,So,直接贴核心代码吧~

核心代码:

private void PostByHttpClient(final String url)

new Thread()

public void run()

try
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List params = new ArrayList();
params.add(new BasicNameValuePair(“user”, “猪大哥”));
params.add(new BasicNameValuePair(“pawd”, “123”));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,“UTF-8”);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200)
HttpEntity entity2 = httpResponse.getEntity();
detail = EntityUtils.toString(entity2, “utf-8”);
handler.sendEmptyMessage(SHOW_DATA);

catch(Exception e)e.printStackTrace();
;
.start();

3.HttpClient抓数据示例(教务系统数据抓取)
其实关于HttpClient的例子有很多,比如笔者曾经用它来抓学校教务系统上学生的课程表: 这就涉及到Cookie,模拟登陆的东西,说到抓数据(爬虫),一般我们是搭配着JSoup来解析 抓到数据的,有兴趣可以自己查阅相关资料,这里贴下笔者毕设app里获取网页部分的关键 代码!大家可以体会下:

HttpClient可以通过下述代码获取与设置Cookie: HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin); 获得Cookie:cookie = loginResponse.getFirstHeader(“Set-Cookie”).getValue(); 请求时带上Cookie:httpPost.setHeader(“Cookie”, cookie);

//获得链接,模拟登录的实现:
public int getConnect(String user, String key) throws Exception
// 先发送get请求 获取cookie值和__ViewState值
HttpGet getLogin = new HttpGet(true_url);
// 第一步:主要的HTML:
String loginhtml = “”;
HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin);
if (loginResponse.getStatusLine().getStatusCode() == 200)
HttpEntity entity = loginResponse.getEntity();
loginhtml = EntityUtils.toString(entity);
// 获取响应的cookie值
cookie = loginResponse.getFirstHeader(“Set-Cookie”).getValue();
System.out.println("cookie= " + cookie);

// 第二步:模拟登录
// 发送Post请求,禁止重定向
HttpPost httpPost = new HttpPost(true_url);
httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);

// 设置Post提交的头信息的参数
httpPost.setHeader("User-Agent",
        "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
httpPost.setHeader("Referer", true_url);
httpPost.setHeader("Cookie", cookie);

// 设置请求数据
List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("__VIEWSTATE",
        getViewState(loginhtml)));// __VIEWSTATE参数,如果变化可以动态抓取获取
params.add(new BasicNameValuePair("Button1", ""));
params.add(new BasicNameValuePair("hidPdrs", ""));
params.add(new BasicNameValuePair("hidsc", ""));
params.add(new BasicNameValuePair("lbLanguage", ""));
params.add(new BasicNameValuePair("RadioButtonList1", "%D1%A7%C9%FA"));
params.add(new BasicNameValuePair("txtUserName", user));
params.add(new BasicNameValuePair("TextBox2", key));
params.add(new BasicNameValuePair("txtSecretCode", "")); // ( ╯□╰ )逗比正方,竟然不需要验证码

// 设置编码方式,响应请求,获取响应状态码:
httpPost.setEntity(new UrlEncodedFormEntity(params, "gb2312"));
HttpResponse response = new DefaultHttpClient().execute(httpPost);
int Status = response.getStatusLine().getStatusCode();
if(Status == 200)return Status;
System.out.println("Status= " + Status);

// 重定向状态码为302
if (Status == 302 || Status == 301) 
    // 获取头部信息中Location的值
    location = response.getFirstHeader("Location").getValue();
    System.out.println(location);
    // 第三步:获取管理信息的主页面
    // Get请求
    HttpGet httpGet = new HttpGet(ip_url + location);// 带上location地址访问
    httpGet.setHeader("Referer", true_url);
    httpGet.setHeader("Cookie", cookie);

    // 主页的html
    mainhtml = "";
    HttpResponse httpResponseget = new DefaultHttpClient()
            .execute(httpGet);
    if (httpResponseget.getStatusLine().getStatusCode() == 200) 
        HttpEntity entity = httpResponseget.getEntity();
        mainhtml = EntityUtils.toString(entity);
    


return Status;


4.使用HttpPut发送Put请求
示例代码如下:

public static int PutActCode(String actCode, String licPlate, Context mContext)
int resp = 0;
String cookie = (String) SPUtils.get(mContext, “session”, “”);
HttpPut httpPut = new HttpPut(PUTACKCODE_URL);
httpPut.setHeader(“Cookie”, cookie);
try

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("activation_code", actCode));
    params.add(new BasicNameValuePair("license_plate", licPlate));
    httpPut.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    HttpResponse course_response = new DefaultHttpClient().execute(httpPut);
    if (course_response.getStatusLine().getStatusCode() == 200) 
        HttpEntity entity2 = course_response.getEntity();
        JSONObject jObject = new JSONObject(EntityUtils.toString(entity2));
        resp = Integer.parseInt(jObject.getString("status_code"));
        return resp;
    
 catch (Exception e) 
    e.printStackTrace();

return resp;

android中Post方式发送HTTP请求

通过Post方式发送HTTP请求的代码逻辑,代码在Eclipse中实现

 

一.主要步骤

1.准备数据装入mydata(一个字节数组)

2.建立连接,设置请求体

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 

connection.setConnectTimeout(3000);
connection.set...;      //设置请求体
connection.connect;

3.通过连接输出数据

OutputStream outputStream = connection.getOutputStream(); 

outputStream.write(mydata,0,mydata.length);

4.通过连接获取服务器返回结果

connection.getInputStream()

 

二.demo 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLEncoder; 
import java.util.HashMap; 
import java.util.Map; 
   
public class HttpUtils { 
   
    private static String PATH = "http://172.24.87.47:8088/myhttp/servlet/LoginAction"; 
    private static URL url; 
    public HttpUtils() {} 
   
    static{ 
        try { 
            url = new URL(PATH); 
        } catch (MalformedURLException e) { 
            e.printStackTrace(); 
        } 
    } 
  
public static void main(String[] arsg){ 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("username", "lili"); 
        params.put("password", "123"); 
        String result = sendPostMessage(params,"utf-8"); 
        System.out.println("result->"+result); 
    }

/**
     * @param params 填写的url的参数
     * @param encode 字节编码
     * @return
     */ 
    public static String sendPostMessage(Map<String, String> params,String encode){ 
        StringBuffer buffer = new StringBuffer(); 
        try {//把请求的主体写入正文!! 
             if(params != null&&!params.isEmpty()){ 
                //迭代器 
          //Map.Entry 是Map中的一个接口,他的用途是表示一个映射项(里面有Key和Value)
           for(Map.Entry<String, String> entry : params.entrySet()){ buffer.append(entry.getKey()).append("="). append(URLEncoder.encode(entry.getValue(),encode)). append("&"); } } // System.out.println(buffer.toString()); //删除最后一个字符&,多了一个;主体设置完毕 buffer.deleteCharAt(buffer.length()-1); byte[] mydata = buffer.toString().getBytes(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3000); connection.setDoInput(true);//表示从服务器获取数据 connection.setDoOutput(true);//表示向服务器写数据 connection.setRequestMethod("POST"); //是否使用缓存 connection.setUseCaches(false); //表示设置请求体的类型是文本类型 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", String.valueOf(mydata.length)); connection.connect(); //连接,不写也可以。。??有待了解 //获得输出流,向服务器输出数据 OutputStream outputStream = connection.getOutputStream(); outputStream.write(mydata,0,mydata.length); //获得服务器响应的结果和状态码 int responseCode = connection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ return changeInputeStream(connection.getInputStream(),encode); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } /** * 将一个输入流转换成字符串 * @param inputStream * @param encode * @return */ private static String changeInputeStream(InputStream inputStream,String encode) { //通常叫做内存流,写在内存中的 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; String result = ""; if(inputStream != null){ try { while((len = inputStream.read(data))!=-1){ data.toString(); outputStream.write(data, 0, len); } //result是在服务器端设置的doPost函数中的 result = new String(outputStream.toByteArray(),encode); outputStream.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } }
 

 参考文章:https://www.cnblogs.com/jycboy/p/post01.html   作者:超超boy

 

以上是关于Android HTTP请求方式的主要内容,如果未能解决你的问题,请参考以下文章

Android HTTP请求方式

android中Post方式发送HTTP请求

Android客户端采用Http 协议Post方式请求与服务端进行数据交互

Android——JDK的get请求方式

Android传统HTTP请求get----post方式提交数据(包括乱码问题)

*** 以编程方式 android