android 向serverGet和Post请求的两种方式,android向server发送文件,自己组装协议和借助第三方开源
一个适用于Android平台的第三方和apache的非常多东西类似,仅仅是用于Android上
我在项目里用的是这个
https://github.com/loopj/android-async-http
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(JsonKey.JSON_K_MOBILE, "1526808");
params.put(JsonKey.JSON_K_COUPON, coupon);
put(File,...);
/**
* @author intbird@163.com
* @time 20140606
*/
package com.intbird.utils; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message; public class ConnInternet {
/**
* 開始连接
*/
public static int HTTP_STATUS_START=0;
/**
* 连接过程出错
*/
public static int HTTP_STATUS_ERROR=400;
/**
* 请求成功,返回数据
*/
public static int HTTP_STATUS_REULTOK=200;
/**
* server未响应
*/
public static int HTTP_STATUS_NORESP=500; /**
* 普通GET请求
* @param api
* @param callBack
*/
public static void get1(final String api,final ConnInternetCallback callBack) {
final Handler handler=getHandle(api, callBack);
new Thread(){
@Override
public void run() {
Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始连接");
try {
URL url = new URL(api);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
int resCode=urlConn.getResponseCode();
if(resCode!=HTTP_STATUS_REULTOK){
msg.what=HTTP_STATUS_NORESP;
msg.obj=resCode;
handler.sendMessage(msg);
return ;
}
InputStreamReader inStream=new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer=new BufferedReader(inStream); String result="";
String inputLine=null;
while((inputLine=buffer.readLine())!=null){
result+=inputLine;
}
msg.what=HTTP_STATUS_REULTOK;
msg.obj=URLDecoder.decode(result,"UTF-8"); inStream.close();
urlConn.disconnect();
} catch (Exception ex) {
msg.what=HTTP_STATUS_ERROR;
msg.obj=ex.getMessage().toString();
}
finally{
handler.sendMessage(msg);
}
}
}.start();
} public void get3(final String api,final ConnInternetCallback callBack) {
final Handler handler=getHandle(api, callBack);
new Thread(){
@Override
public void run() {
Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始连接");
try {
HttpGet httpGet=new HttpGet(api);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResp = httpClient.execute(httpGet); int resCode=httpResp.getStatusLine().getStatusCode();
if(resCode!=HTTP_STATUS_REULTOK){
msg.what=HTTP_STATUS_NORESP;
msg.obj=resCode;
handler.sendMessage(msg);
return ;
}
msg.what=HTTP_STATUS_REULTOK;
msg.obj= EntityUtils.toString(httpResp.getEntity()); }catch (Exception e) {
msg.what=HTTP_STATUS_ERROR;
msg.obj= e.getMessage();
}
finally{
handler.sendMessage(msg);
}
}
}.start();
} private static Handler getHandle(final String api,final ConnInternetCallback callBack){
return new Handler() {
@Override
public void handleMessage(Message message) {
//不 在 这里写!
callBack.callBack(message.what,api, message.obj.toString());
}
};
} /**
* 简单类型,仅仅进行文字信息的POST;
* @param api api地址
* @param params 仅字段參数
* @param callBack 返回调用;
*/
public static void post1(final String api,final HashMap<String,String> params,final ConnInternetCallback callBack){
final Handler handler=getHandle(api, callBack);
new Thread(){
@Override
public void run() {
Message msg=handler.obtainMessage(HTTP_STATUS_START,"開始连接");
try {
URL url=new URL(api);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConn.setRequestProperty("Charset", "UTF-8"); urlConn.connect();
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
Iterator<String> iterator=params.keySet().iterator();
while(iterator.hasNext()){
String key= iterator.next();
String value= URLEncoder.encode(params.get(key),"UTF-8");
out.write((key+"="+value+"&").getBytes());
}
out.flush();
out.close(); int resCode=urlConn.getResponseCode();
if(resCode!=HTTP_STATUS_REULTOK){
msg.what=HTTP_STATUS_NORESP;
msg.obj=resCode;
handler.sendMessage(msg);
return ;
}
String result="";
String readLine=null;
InputStreamReader inputStream=new InputStreamReader(urlConn.getInputStream());
BufferedReader bufferReader=new BufferedReader(inputStream);
while((readLine=bufferReader.readLine())!=null){
result+=readLine;
}
msg.what=HTTP_STATUS_REULTOK;
msg.obj=URLDecoder.decode(result,"UTF-8");
inputStream.close();
bufferReader.close();
urlConn.disconnect();
}catch(Exception ex){
msg.what=HTTP_STATUS_ERROR;
msg.obj=ex.getMessage().toString()+".";
}
finally{
handler.sendMessage(msg);
}
}
}.start();
} /**
* 自己定义文字和文件传输协议[演示样例在函数结尾];
* @param apiUrl api地址
* @param mapParams 文字字段參数
* @param listUpFiles 多文件參数
* @param callBack 返回调用;
*/
public static void post2(final String apiUrl,final HashMap<String,String> mapParams,final ArrayList<ConnInternetUploadFile> listUpFiles,ConnInternetCallback callBack){
final Handler handler=getHandle(apiUrl, callBack);
new Thread(new Runnable() {
public void run() {
Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始连接"); String BOUNDARY="———7d4a6454354fe54scd";
String PREFIX="--";
String LINE_END="\r\n"; try{
URL url=new URL(apiUrl);
HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Charset", "UTF-8");
urlConn.setRequestProperty("Content-Type","multipart/form-data ;boundary="+BOUNDARY); DataOutputStream outStream=new DataOutputStream(urlConn.getOutputStream()); for(Map.Entry<String,String> entry:mapParams.entrySet()){
StringBuilder sbParam=new StringBuilder();
sbParam.append(PREFIX);
sbParam.append(BOUNDARY);
sbParam.append(LINE_END);
sbParam.append("Content-Disposition:form-data;name=\""+ entry.getKey()+"\""+LINE_END);
sbParam.append("Content-Transfer-Encoding: 8bit" + LINE_END);
sbParam.append(LINE_END);
sbParam.append(entry.getValue());
sbParam.append(LINE_END);
outStream.write(sbParam.toString().getBytes());
} for(ConnInternetUploadFile file:listUpFiles){
StringBuilder sbFile=new StringBuilder();
sbFile.append(PREFIX);
sbFile.append(BOUNDARY);
sbFile.append(LINE_END);
sbFile.append("Content-Disposition:form-data;name=\""+file.getFormname()+"\";filename=\""+file.getFileName()+"\""+LINE_END);
sbFile.append("Content-type:"+file.getContentType()+"\""+LINE_END);
outStream.write(sbFile.toString().getBytes());
writeFileToOutStream(outStream,file.getFileUrl());
outStream.write(LINE_END.getBytes("UTF-8"));
} byte[] end_data=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes("UTF-8");
outStream.write(end_data);
outStream.flush();
outStream.close(); int resCode=urlConn.getResponseCode();
if(resCode!=HTTP_STATUS_REULTOK){
msg.what=HTTP_STATUS_NORESP;
msg.obj=resCode;
handler.sendMessage(msg);
return ;
}
String result="";
String readLine=null;
InputStreamReader inputStream=new InputStreamReader(urlConn.getInputStream());
BufferedReader bufferReader=new BufferedReader(inputStream);
while((readLine=bufferReader.readLine())!=null){
result+=readLine;
}
msg.what=HTTP_STATUS_REULTOK;
msg.obj=URLDecoder.decode(result,"UTF-8");
inputStream.close();
bufferReader.close();
urlConn.disconnect();
}catch(Exception ex){
msg.what=HTTP_STATUS_ERROR;
msg.obj=ex.getMessage().toString();
}
finally{
handler.sendMessage(msg);
}
}
}).start();
// HashMap<String,String> params=new HashMap<String, String>();
// params.put("pid", fileHelper.getShareProf("PassportId"));
// params.put("json",postJson(text)); // ArrayList<UploadFile> uploadFiles=new ArrayList<UploadFile>();
// if(url.length()>0){
// UploadFile upfile=new UploadFile(url,url,"Images");
// uploadFiles.add(upfile);
// }
// Internet.post(Api.api_messageCreate, params,uploadFiles,new InternetCallback() {
// @Override
// public void callBack(int msgWhat, String api, String result) {
// if(msgWhat==Internet.HTTP_STATUS_OK){
// //跟新数据
// adapter.notifyDataSetChanged();
// //显示没有数据
// }else showToast("网络错误");
// }
// });
} /**
* 第三方Apache集成POST
* @param url api地址
* @param mapParams 參数
* @param callBack
*/
public static void post3(final String url, final HashMap<String,String> mapParams,final HashMap<String,String> mapFileInfo,ConnInternetCallback callBack) {
final Handler handler=getHandle(url , callBack);
new Thread() {
@Override
public void run() {
Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始连接");
try {
HttpPost httpPost = new HttpPost(url);
//多类型;
MultipartEntity multipartEntity = new MultipartEntity();
//字段
Iterator<? > it=mapParams.keySet().iterator();
while(it.hasNext()){
String key=(String) it.next();
String value=mapParams.get(key);
multipartEntity.addPart(key,new StringBody(value,Charset.forName("UTF-8")));
}
//文件
it=mapFileInfo.keySet().iterator();
while(it.hasNext()){
String key=(String)it.next();
String value=mapFileInfo.get(key);
multipartEntity.addPart(key, new FileBody(new File(value)));
} httpPost.setEntity(multipartEntity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResp = httpClient.execute(httpPost); int resCode=httpResp.getStatusLine().getStatusCode();
if(resCode!=HTTP_STATUS_REULTOK){
msg.what=HTTP_STATUS_NORESP;
msg.obj=resCode;
handler.sendMessage(msg);
return ;
}
msg.what=HTTP_STATUS_REULTOK;
msg.obj= EntityUtils.toString(httpResp.getEntity()); }catch (Exception e) {
msg.what=HTTP_STATUS_ERROR;
msg.obj= e.getMessage();
}
finally{
handler.sendMessage(msg);
}
}
}.start();
} public static Bitmap loadBitmapFromNet(String imgUrl,BitmapFactory.Options options){
Bitmap bitmap = null;
URL imageUrl = null;
if (imgUrl == null || imgUrl.length() == 0) return null;
try {
imageUrl = new URL(imgUrl);
URLConnection conn = imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
int length = conn.getContentLength();
if (length != -1) {
byte[] imgData = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) != -1) {
System.arraycopy(temp, 0, imgData, destPos, readLen);
destPos += readLen;
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);
options.inJustDecodeBounds=false;
bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);
}
} catch (IOException e) {
return null;
}
return bitmap;
} public static void writeFileToOutStream(DataOutputStream outStream,String url){
try {
InputStream inputStream = new FileInputStream(new File(url));
int ch;
while((ch=inputStream.read())!=-1){
outStream.write(ch);
}
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
} public interface ConnInternetCallback{
public void callBack(int msgWhat,String api,String result);
} public class ConnInternetUploadFile {
private String filename;
private String fileUrl;
private String formname;
private String contentType = "application/octet-stream";
//image/jpeg
public ConnInternetUploadFile(String filename, String fileUrl, String formname) {
this.filename = filename;
this.fileUrl=fileUrl;
this.formname = formname;
} public String getFileUrl() {
return fileUrl;
} public void setFileUrl(String url) {
this.fileUrl=url;
} public String getFileName() {
return filename;
} public void setFileName(String filename) {
this.filename = filename;
} public String getFormname() {
return formname;
} public void setFormname(String formname) {
this.formname = formname;
} public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
} }
android 向serverGet和Post请求的两种方式,android向server发送文件,自己组装协议和借助第三方开源的更多相关文章
- 怎样在Android开发中FPS游戏实现的两种方式比较
怎样在Android开发中FPS游戏实现的两种方式比较 如何用Android平台开发FPS游戏,其实现过程有哪些方法,这些方法又有哪些不同的地方呢?首先让我们先了解下什么是FPS 英文名:FPS (F ...
- 第二节:SSL证书的申请、配置(IIS通用)及跳转Https请求的两种方式
一. 相关概念介绍 1. SSL证书服务 SSL证书服务由"服务商"联合多家国内外数字证书管理和颁发的权威机构.在xx云平台上直接提供的服务器数字证书.您可以在阿里云.腾讯云等平台 ...
- [Android] Android ViewPager 中加载 Fragment的两种方式 方式(二)
接上文: https://www.cnblogs.com/wukong1688/p/10693338.html Android ViewPager 中加载 Fragmenet的两种方式 方式(一) 二 ...
- [Android] Android ViewPager 中加载 Fragment的两种方式 方式(一)
Android ViewPager 中加载 Fragmenet的两种方式 一.当fragment里面的内容较少时,直接 使用fragment xml布局文件填充 文件总数 布局文件:view_one. ...
- C#中Post请求的两种方式发送参数链和Body的
POST请求 有两种方式 一种是组装key=value这种参数对的方式 一种是直接把一个字符串发送过去 作为body的方式 我们在postman中可以看到 sfdsafd sdfsdfds publi ...
- 解决 SharePoint 2010 拒绝访问爬网内容源错误的小技巧(禁用环回请求的两种方式)
这里有一条解决在SharePoint 2010搜索爬网时遇到的“拒绝访问错误”的小技巧. 首先要检查默认内容访问帐户是否具有相应的访问权限,或者添加一条相应的爬网规则.如果目标资源库是一个ShareP ...
- Android中H5和Native交互的两种方式
Android中H5和Native交互的两种方式:http://www.jianshu.com/p/bcb5d8582d92 注意事项: 1.android给h5页面注入一个对象(WZApp),这个对 ...
- JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理
java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...
- 探讨Netty获取并检查Websocket握手请求的两种方式
在使用Netty开发Websocket服务时,通常需要解析来自客户端请求的URL.Headers等等相关内容,并做相关检查或处理.本文将讨论两种实现方法. 方法一:基于HandshakeComplet ...
随机推荐
- Orchard 源码探索(Application_Start)之异步委托调用
2014年5月26日 10:26:31 晴 ASP.NET 接收到对应用程序中任何资源的第一个请求时,名为ApplicationManager 的类会创建一个应用程序域.应用程序域为全局变量提供应用程 ...
- django note
2016-2-9 Unknown command: 'syncdb' solution: syncdb command is deprecated in django 1.7. Use the py ...
- CF卡是什么
CF卡(Compact Flash)最初是一种用于便携式电子设备的数据存储设备.作为一种存储设备,它革命性的使用了闪存,于1994年首次由SanDisk公司生产并制定了相关规范.当前,它的物理格式已经 ...
- Delphi 实现Ini文件参数与TEdit和TCheckBox绑定(TSimpleParam)
在实际工作中,常遇到对Ini参数的修改,显示与保存问题. 如果手工写代码,会有很大的工作量. 本例把ini文件的参数与控件绑定起来,以达到方便使用的目的. 本例程共有2个单元 uSimpleParam ...
- Android 保存图片到SQLite,读出SQLite中的图片
1.bitmap保存到SQLite 中 数据格式: db.execSQL("Create table express ( _id INTEGER PRIMARY KEY AUTOINCREM ...
- 网易云课堂_C语言程序设计进阶_第5周:链表_1逆序输出的数列
1 逆序输出的数列(10分) 题目内容: 你的程序会读入一系列的正整数,预先不知道正整数的数量,一旦读到-1,就表示输入结束.然后,按照和输入相反的顺序输出所读到的数字,不包括最后标识结束的-1. 输 ...
- 怎么限制Google自己主动调整字体大小
Google默认的字体大小是12px,当样式表中font-size<12px时,或者没有明白指定字体大小,则在chrome浏览器里字体显示是12px. 近期在写代码玩的时候,我也碰到了 在FF和 ...
- 得到client真IP住址
1.引进的必要性log4j-1.2.14.jar package org.ydd.test; import java.util.Enumeration; import javax.servlet.ht ...
- linux 自旋锁
一.概述: 自旋锁是SMP架构中的一种low-level的同步机制.当线程A想要获取一把自旋锁而该锁又被其它线程锁持有时,线程A会在一个循环中自旋以检测锁是不是已经可用了.对于自选锁需要注意: 由于自 ...
- 从零开始学习UNITY3D(GUI篇)
邻近年底,心也有些散乱,加上工作忙了一阵,在达内培训的课程也落下了不少.对unity3d的热度似乎也有点点下降.痛定思痛,又在淘宝上买了写蛮牛网的视频.总之不管是用任何手段都要逼着自己不要浪费了培训的 ...