androidhttppost
‘壹’ android程序发送HttpPost请求访问https
获取数据从网络运营商进入一个线程执行,不会有什么变化异常。 ,BroadcastReceiver的,因为Android系统默认的处理时间为10秒,如果10秒还没有完成,它会报告超时异常!
‘贰’ Android中使用HttpPost实现数据与文件同时上传的功能
第一步:编写一个Servlet,把接收到的HTTP信息保存在一个文件中,代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取输入流,是HTTP协议中的实体内容
ServletInputStream sis=request.getInputStream();
//缓冲区
byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream("d://file.log");
int len=sis.read(buffer, 0, 1024);
//把流里的信息循环读入到file.log文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}
第二步:实现如下图1的的表单页面,生成一个注册表单,提交到Servlet中
详细的代码如下:
<form action="servlet/ReceiveFile" method="post" enctype="multipart/form-data">
第一个参数<input type="text" name="name1"/> <br/>
第二个参数<input type="text" name="name2"/> <br/>
第一个上传的文件<input type="file" name="file1"/> <br/>
第二个上传的文件<input type="file" name="file2"/> <br/>
<input type="submit" value="提交">
</form>
注意了,由于要上传附件,所以一定要设置enctype为multipart/form-data,才可以实现附件的上传。
第三步:填写完信息后按“提交”按钮后,在D盘下查找file.log文件用记事本打开,数据如下:
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="name1"
hello
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="name2"
world
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="file1"; filename="C:/2.GIF"
Content-Type: image/gif
GIF89a
‘叁’ android http post 请求怎么写,我返回的结果不正确
HTTP错误405 – 禁止访问资源. 可能是server端有访问设置.你可以问下做server的人. 或者换一个server做下测试,看到底是server的问题,还是你代码的问题.
java">packagejusi.singporecameratest;
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.protocol.HTTP;
importorg.apache.http.util.EntityUtils;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.widget.TextView;
{
/**.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
DefaultHttpClienthttpClient=newDefaultHttpClient();
Stringurl="http://appschallenge.juzz4.com/api/login";
HttpPosthttppost=newHttpPost(url);
httppost.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair>list=newArrayList<NameValuePair>();
list.add(newBasicNameValuePair("username","demo"));
list.add(newBasicNameValuePair("password","demo"));
list.add(newBasicNameValuePair("mechanism","plain"));
Stringstr=null;
try{
httppost.setEntity(newUrlEncodedFormEntity(list,HTTP.UTF_8));
HttpResponseresponse=httpClient.execute(httppost);
str=EntityUtils.toString(response.getEntity());
}catch(UnsupportedEncodingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
//取得HTTPresponse
catch(ClientProtocolExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
‘肆’ android通过http post实现文件下载
可参照我的如下代码
java.io.OutputStreamos=null;
java.io.InputStreamis=null;
try{
java.io.Filefile=newjava.io.File(str_local_file_path);
if(file.exists()&&file.length()>0){
}else{
file.createNewFile();
java.net.URLurl=newjava.net.URL(str_url);
java.net.HttpURLConnectionconn=(java.net.HttpURLConnection)url.openConnection();
os=newjava.io.FileOutputStream(file);
is=conn.getInputStream();
byte[]buffer=newbyte[1024*4];
intn_rx=0;
while((n_rx=is.read(buffer))>0){
os.write(buffer,0,n_rx);
}
}
returntrue;
}catch(MalformedURLExceptione){
}catch(IOExceptione){
}finally{
os.flush();
os.close();
is.close();
}
returnfalse;
‘伍’ 怎样实现android http-post方法实例说明
代码如下:
package com.hl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
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 android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SimplePOST extends Activity {
private TextView show;
private EditText txt;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
show = (TextView)findViewById(R.id.show);
txt = (EditText)findViewById(R.id.txt);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dopost(txt.getText().toString());
}
});
}
private void dopost(String val){
//封装数据
Map<String, String> parmas = new HashMap<String, String>();
parmas.put("name", val);
DefaultHttpClient client = new DefaultHttpClient();//http客户端
HttpPost httpPost = new HttpPost("http://mhycoe.com/test/post.php");
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
if(parmas != null){
Set<String> keys = parmas.keySet();
for(Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = (String)i.next();
pairs.add(new BasicNameValuePair(key, parmas.get(key)));
}
}
try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, "utf-8");
/*
* 将POST数据放入HTTP请求
*/
httpPost.setEntity(p_entity);
/*
* 发出实际的HTTP POST请求
*/
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String returnConnection = convertStreamToString(content);
show.setText(returnConnection);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
‘陆’ 安卓开发 http中get和post的区别
(一)HttpGet :doGet()方法
//doGet():将参数的键值对附加在url后面来传递
[java] view
plain
public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{
//服务器 :服务器项目 :servlet名称
String path="http://192.168.5.21:8080/test/test";
String uri=path+"?name="+name+"&pwd="+pwd;
//name:服务器端的用户名,pwd:服务器端的密码
//注意字符串连接时不能带空格
String result="";
HttpGet httpGet=new HttpGet(uri);//编者按:与HttpPost区别所在,这里是将参数在地址中传递
HttpResponse response=new DefaultHttpClient().execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}
(二)HttpPost :doPost()方法
//doPost():将参数打包到http报头中传递
[java] view
plain
public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{
//服务器 :服务器项目 :servlet名称
String path="http://192.168.5.21:8080/test/test";
HttpPost httpPost=new HttpPost(path);
List<NameValuePair>list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", name));
list.add(new BasicNameValuePair("pwd", pwd));
httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));//编者按:与HttpGet区别所在,这里是将参数用List传递
String result="";
HttpResponse response=new DefaultHttpClient().execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}
-------------------------------------------------------------------------------------------------------
由此我们可知,HttpGet和HttpPost的区别在于前者是将参数在地址中传递,后者是将参数用List传递。
‘柒’ 求教android中,在使用HttpPost类的时候,在新建的时候一直都在报错
我自己写的自己在用的一个HttpRequestHelper类
/**
* @param HttpPost
* @return HttpRespone
* Describe 用于发送HttpPost请求
*/
public HttpResponse HttpRequestPost(HttpPost postRequest) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(postRequest);
return response;
}
/**
* @param String url
* @param List<headers>
* @param List<BasciNameValuePair>
* @return HttpPost
* Describe HttpPost构造的一种重载
*/
public HttpPost BuildHttpPostRequest(String url,List<org.apache.http.Header> headers,List<BasicNameValuePair> postDatas) throws IOException {
HttpPost postRequest = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (org.apache.http.Header h : headers) {
postRequest.addHeader(h);
}
for (BasicNameValuePair vp : postDatas) {
nvps.add(vp);
}
postRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
return postRequest;
}
使用的例子
Public HttpResponse Demo(){
List<org.apache.http.Header> headers = new ...
List<BasicNameValuePari> postDatas = new...
headers.add(new BasicHeader("xxx","xxx"));
.
.
.
postDatas.add(new BasicNameValuePair("xxx","xxx"));
.
.
.
HttpRequestHelper helper = new ..
HttpPost post = helper.BuildHttpPostRequest(URL,headers,postDatas);
HttpResponse response = helper.HttpRequestPost(post);
return reponse;
}
‘捌’ Android HTTP Post请求错误400
你确定你的post方法调用的url没问题吗?参数的名称和个数也没问题吗?
‘玖’ android httppost类在哪
虽然在登录系统中使用了Web Service与服务端进行交互。但是在传递大量的数量时,Web Service显得有些笨拙。在本节将介绍移动电子相册中使用的另外一种与数据库交互的方法。直接发送HTTP GET或POST请求。这就要用到HttpGet、HttpPost以及HttpURLConnection这些类。
15.3.1 HttpGet类和HttpPost类
本节将介绍Android SDK集成的Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),而不是Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。
在HttpClient模块中用到了两个重要的类:HttpGet和HttpPost。这两个类分别用来提交HTTP GET和HTTP POST请求。为了测试本节的例子,需要先编写一个Servlet程序,用来接收HTTP GET和HTTP POST请求。读者也可以使用其他服务端的资源来测试本节的例子。
假设192.168.17.81是本机的IP,客户端可以通过如下的URL来访问服务端的资源:
http://192.168.17.81:8080/querybooks/QueryServlet?bookname=开发
在这里bookname是QueryServlet的请求参数,表示图书名,通过该参数来查询图书信息。
现在我们要通过HttpGet和HttpPost类向QueryServlet提交请求信息,并将返回结果显示在TextView组件中。
无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。
1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
‘拾’ android OKhttp 异步POST请求
可以采用okGo 开实现,
OkGo.<String>post(BASEURL + "/test/deviceInfo")
.upJson(jsonObject)
.execute(callback);
然后在
@Override
public void onSuccess(Response<String> response) {} 内进行处理