博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android—网络请求
阅读量:4352 次
发布时间:2019-06-07

本文共 3861 字,大约阅读时间需要 12 分钟。

import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;/** * Connect to the internet *  * @author crane *  */public class HttpTools {    /**     * Post data to server     *      * @param sUrl     * @param entity     * @return     */    public static String postData(String sUrl, MultipartEntity entity) {        String destUrl = "";        destUrl = sUrl;        String sResult = "";        // instantiate HttpPost object from the url address        HttpEntityEnclosingRequestBase httpRequest = new HttpPost(destUrl);        try {            httpRequest.setEntity(entity);            // execute the post and get the response from servers            HttpResponse httpResponse = new DefaultHttpClient()                    .execute(httpRequest);            int code = httpResponse.getStatusLine().getStatusCode();            if (httpResponse.getStatusLine().getStatusCode() == 200) {                // get the result                String strResult = EntityUtils.toString(httpResponse                        .getEntity());                sResult = strResult;                System.out.println(strResult);            } else {                System.out.println("Error Response"                        + httpResponse.getStatusLine().toString());            }        } catch (Exception e) {            System.out.println("error occurs");        }        return sResult;    }    /**     * Get data from server     *      * @param urlPath     * @return     */    public static String getData(String sUrl) {        String urlPath = sUrl;        ByteArrayOutputStream outStream = null;        String sResult = "";        try {            outStream = new ByteArrayOutputStream();            byte[] data = new byte[1024];            int len = 0;            URL url = new URL(urlPath);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            InputStream inStream = conn.getInputStream();            while ((len = inStream.read(data)) != -1) {                outStream.write(data, 0, len);            }            inStream.close();            sResult = new String(outStream.toByteArray()).trim();        } catch (Exception e) {            e.printStackTrace();        }        return sResult;    }    public static String post(String sUrl, List
parameters) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(sUrl); String sResult = ""; try { HttpEntity entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8); // 设置编码,防止中文乱码 httpPost.setEntity(entity); // httpClient执行httpPost表单提交 HttpResponse response = httpClient.execute(httpPost); // 得到服务器响应实体对象 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { sResult = EntityUtils.toString(responseEntity, "utf-8"); System.out.println("表单上传成功!"); } else { System.out.println("服务器无响应!"); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 httpClient.getConnectionManager().shutdown(); } return sResult.replace(",", ","); }} 所需jar包:

 

转载于:https://www.cnblogs.com/crane13/p/3688366.html

你可能感兴趣的文章
ElasticSearch(二十六)修改分词器及定制自己的分词器
查看>>
(原创)用c++11打造好用的any
查看>>
洛谷 P2947 [USACO09MAR]向右看齐Look Up【单调栈】
查看>>
POJ 3070 Fibonacci【斐波那契数列/矩阵快速幂】
查看>>
uva 11724 Evaluate the Expression
查看>>
QQ微博登陆封装
查看>>
例4-11
查看>>
poj3565Ants——KM算法
查看>>
bzoj1588 [HNOI2002]营业额统计——双向链表
查看>>
CRM WEB UI 04明细界面添加按钮
查看>>
IOS8后UIImagePickConroller警告提示解决方法
查看>>
自动化mobile测试
查看>>
sql
查看>>
C# PrintDocument打印
查看>>
indexof 和 indexofany有什么区别
查看>>
Ruby基础教程
查看>>
R语言学习——实例标识符
查看>>
C++设计模式 之 “对象创建”模式:Factory Method、Abstract Factory、Prototype、Builder...
查看>>
201521123055 《Java程序设计》第3周学习总结
查看>>
双线性插值原理与实现
查看>>