Android HttpClient GET或者POST请求基本使用方法(android的http)
25-03-12
10
对于AndroidHttpClientGET或者POST请求基本使用方法感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解android的http,并且为您提供关于AndroidHttpCli
对于Android HttpClient GET或者POST请求基本使用方法 感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解android的http ,并且为您提供关于Android HttpClient,DefaultHttpClient,HttpPost、android – 使用HttpClient的HTTP请求太慢了?、android – 如何在httppost / httpget请求中设置标头、Android 使用 httpClient 取消http请求的方法 的宝贵知识。
本文目录一览:
Android HttpClient GET或者POST请求基本使用方法(android的http) 在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求(当然它的功能远不止这些)
这里只介绍如何使用HttpClient发起GET或者POST请求
GET 方式
//先将参数放入List,再对参数进行URL编码 List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("param1","中国")); params.add(new BasicNameValuePair("param2","value2")); //对参数编码 String param = URLEncodedUtils.format(params,"UTF-8"); //baseUrl String baseUrl = "http://ubs.free4lab.com/PHP/method.PHP"; //将URL与参数拼接 HttpGet getmethod = new HttpGet(baseUrl + "?" + param); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(getmethod); //发起GET请求 Log.i(TAG,"resCode = " + response.getStatusLine().getStatusCode()); //获取响应码 Log.i(TAG,"result = " + EntityUtils.toString(response.getEntity(),"utf-8"));//获取服务器响应内容 } catch (ClientProtocolException e) { // Todo Auto-generated catch block e.printstacktrace(); } catch (IOException e) { // Todo Auto-generated catch block e.printstacktrace(); } POST方式
//和GET方式一样,先将参数放入List params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("param1","Post方法")); params.add(new BasicNameValuePair("param2","第二个参数")); try { HttpPost postMethod = new HttpPost(baseUrl); postMethod.setEntity(new UrlEncodedFormEntity(params,"utf-8")); //将参数填入POST Entity中 HttpResponse response = httpClient.execute(postMethod); //执行POST方法 Log.i(TAG,"utf-8")); //获取响应内容 } catch (UnsupportedEncodingException e) { // Todo Auto-generated catch block e.printstacktrace(); } catch (ClientProtocolException e) { // Todo Auto-generated catch block e.printstacktrace(); } catch (IOException e) { // Todo Auto-generated catch block e.printstacktrace(); }
Android HttpClient,DefaultHttpClient,HttpPost 我如何将字符串数据(
JSONObject.toString())发送到URL.我想在util类中编写一个静态方法来执行此操作.我希望方法签名如下
public static String postData(String url,String postData)抛出SomeCustomException
字符串url的格式应该是什么
返回String是来自服务器的响应,作为json数据的字符串表示.
编辑
目前的连接工具
package my.package;
import my.package.exceptions.CustomException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import org.apache.http.httpentity;
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.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class ConnectionUtil {
public static String postData(String url,String postData)
throws CustomException {
// Create a new HttpClient and Post Header
InputStream is = null;
StringBuilder sb = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost();
httppost.setHeader("host",url);
Log.v("ConnectionUtil","opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url));
try {
httppost.setEntity(new StringEntity(postData));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
httpentity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag","Error in http connection " + e.toString());
e.printstacktrace();
throw new CustomException("Could not establish network connection");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is,"utf-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag","Error converting result " + e.toString());
throw new CustomException("Error parsing the response");
}
Log.v("ConnectionUtil","Sent: "+postData);
Log.v("ConnectionUtil","Got result "+result);
return result;
}
}
Logcat输出
10-16 11:27:27.287: E/log_tag(4935): Error in http connection java.lang.NullPointerException 10-16 11:27:27.287: W/System.err(4935): java.lang.NullPointerException 10-16 11:27:27.287: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496) 10-16 11:27:27.307: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-16 11:27:27.327: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1) 10-16 11:27:27.327: W/System.err(4935): at android.os.AsyncTask$2.call(AsyncTask.java:185) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 10-16 11:27:27.327: W/System.err(4935): at java.lang.Thread.run(Thread.java:1019) 10-16 11:27:27.327: V/log_tag(4935): Could not establish network connection
解决方法
我认为在您的代码中,基本问题是由您使用StringEntity将参数POST到网址的方式引起的.检查以下代码是否有助于使用StringEntity将数据发布到服务器.
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username",username);
jsonObj.put("data",dataValue);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(),HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
希望这有助于解决您的问题.谢谢.
android – 使用HttpClient的HTTP请求太慢了?
我正在尝试编写一个
Android应用程序,它将一些帖子值发送到托管在专用服务器上的PHP文件并存储数组resoult
代码是这样的
HttpPost httppost;
DefaultHttpClient httpclient;
httppost = new HttpPost("http://IP/script.PHP");
HttpParams param = new BasicHttpParams();
param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
// httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
HttpProtocolParams.setContentCharset(param,"UTF-8");
httpclient = new DefaultHttpClient(param);
ResponseHandler <String> res=new BasicResponseHandler();
List<NameValuePair> nameValuePairs;
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id","1"));
nameValuePairs.add(new BasicNameValuePair("api","1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.v("1",System.currentTimeMillis()+"");// Log to kNow the time diff
String result= httpclient.execute(httppost,res);
Log.v("2",System.currentTimeMillis()+""); // Log to kNow the time diff
这段代码浪费了大约2.5秒(在3G或WiFi上)发送帖子并从服务器获得“ok”字符串,即使有好的wifi这次只下来2.2 / 2.0秒
我在我的计算机上运行了一个简单的Ajax发送邮件脚本,通过同一部手机和3G连接到互联网,需要大约.300ms才能做同样的事情¿相同的连接,相同的动作,2秒的差异?
/// *** UPDATE
我在我的计算机上再次尝试了我的jquery脚本(带有移动3G / HDSPA连接)
平均时间响应约为250毫秒,但总是第一次请求高达1.7秒,我试图发送间隔为30秒的帖子,我得到平均1.5秒的时间,然后我试图发送间隔为2秒的帖子,第一次是1.41s,接近252ms
在这里,你们可以查看图表:http://i46.tinypic.com/27zjl8n.jpg
这种与电缆连接(标准家庭DSL)相同的测试始终提供约170ms间隔的固定时间响应(这里没有可靠的参数,但恕我直言,可能第一次尝试略高一点)
因此,在第一次尝试中有一些(或错误的)严重影响移动连接的东西,任何想法的人?
解决方法
尝试使用此配置
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = httpclient.getParams();
httpconnectionParams.setConnectionTimeout(httpParameters,CONNECTION_TIMEOUT);
httpconnectionParams.setSoTimeout(httpParameters,WAIT_RESPONSE_TIMEOUT);
httpconnectionParams.setTcpNoDelay(httpParameters,true);
这是关于setTcpNoDelay的javadoc:
public static void setTcpNoDelay(HttpParams params,boolean value)
Since: API Level 1
Determines whether Nagle’s algorithm is to be used. The Nagle’s algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance,they can disable Nagle’s algorithm (that is enable TCP_NODELAY). Data will be sent earlier,at the cost of an increase in bandwidth consumption.
Parameters
value true if the Nagle’s algorithm is to NOT be used (that is enable TCP_NODELAY),false otherwise.
android – 如何在httppost / httpget请求中设置标头 我有一个像“post -H”授权的Web服务:令牌令牌=“2hwhdh443hdhfh43j3jdej3j3”’.如何在httpPost / get请求中设置此头.
我的代码在这里 –
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(MainActivity.baseUrl
+ "messages");
request.setHeader(new BasicHeader("Content-Type","application/json"));
request.setHeader(new BasicHeader("Authorization: Token","token= 2hwhdh443hdhfh43j3jdej3j3"));
response = client.execute(request);
但这会给出HTML响应.请任何人都可以指导我.
解决方法:
尝试删除“Content-Type”标题并将“Authorization”修改为 –
request.addHeader("Authorization","Token token=2hwhdh443hdhfh43j3jdej3j3");
为我工作
Android 使用 httpClient 取消http请求的方法 其实apache还是提供了释放 连接资源的方法的,不过是埋得深了点。
httpClient.getConnectionManager().shutdown();
这个shutdown并不是将手机网络断掉,而是将建立Http连接请求时所分配的资源释放掉。
今天关于Android HttpClient GET或者POST请求基本使用方法 和android的http 的介绍到此结束,谢谢您的阅读,有关Android HttpClient,DefaultHttpClient,HttpPost、android – 使用HttpClient的HTTP请求太慢了?、android – 如何在httppost / httpget请求中设置标头、Android 使用 httpClient 取消http请求的方法 等更多相关知识的信息可以在本站进行查询。