如果您想了解Android,Java:HTTPPOST请求和androidhandlerpost的知识,那么本篇文章将是您的不二之选。我们将深入剖析Android,Java:HTTPPOST请求的各个
如果您想了解Android,Java:HTTP POST请求和android handler post的知识,那么本篇文章将是您的不二之选。我们将深入剖析Android,Java:HTTP POST请求的各个方面,并为您解答android handler post的疑在这篇文章中,我们将为您介绍Android,Java:HTTP POST请求的相关知识,同时也会详细的解释android handler post的运用方法,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- Android,Java:HTTP POST请求(android handler post)
- android http post 请求获取 json 图片
- Android HttpClient GET或者POST请求基本使用方法
- Android post请求
- Android studio使用OKGO的POST请求访问http失败的解决方法
Android,Java:HTTP POST请求(android handler post)
我必须向网络服务发出http发布请求,以使用用户名和密码对用户进行身份验证。Web服务人员向我提供了以下信息,以构造HTTP Post请求。
POST /login/dologin HTTP/1.1Host: webservice.companyname.comContent-Type: application/x-www-form-urlencodedContent-Length: 48id=username&num=password&remember=on&output=xml
我将得到的XML响应是
<?xml version="1.0" encoding="ISO-8859-1"?><login> <message><![CDATA[]]></message> <status><![CDATA[true]]></status> <Rlo><![CDATA[Username]]></Rlo> <Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc> <Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm> <Rl><![CDATA[username@company.com]]></Rl> <uid><![CDATA[3539145]]></uid> <Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu></login>
这就是我正在做的HttpPost postRequest = new HttpPost(urlString); 我该如何构造其余参数?
答案1
小编典典这是之前在androidsnippets.com
上找到的示例(该站点目前不再维护)。
// Create a new HttpClient and Post HeaderHttpClient httpclient = new DefaultHttpClient();HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost);} catch (ClientProtocolException e) { // TODO Auto-generated catch block} catch (IOException e) { // TODO Auto-generated catch block}
因此,你可以将参数添加为BasicNameValuePair
。
另一种方法是使用(Http)URLConnection
。另请参见使用java.net.URLConnection
触发和处理HTTP请求。实际上,这是较新的Android版本(Gingerbread +
)中的首选方法。另请参见此博客,此开发人员文档和Android的HttpURLConnectionjavadoc
。
android http post 请求获取 json 图片
public class SuperAsyncHttp {
Context context;
/**
* 单例模式
*/
private static SuperAsyncHttp superAsyncHttp=new SuperAsyncHttp();
private SuperAsyncHttp(){}
public static SuperAsyncHttp getInstance(){
if(superAsyncHttp==null){
superAsyncHttp=new SuperAsyncHttp();
}
return superAsyncHttp;
}
/**
* 异步http请求下载图片返回Drawable对象
*/
public Drawable post4Drawable(String url){
HttpPost httpPost=null;
HttpClient httpClient=null;
HttpResponse httpResponse=null;
try{
httpPost=new HttpPost(url);
httpClient=new DefaultHttpClient();
httpResponse=httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode()==200){
InputStream is=httpResponse.getEntity().getContent();
return FormatTools.getInstance().InputStream2Drawable(is);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 异步http请求下载图片返回Bitmap对象
*/
public Bitmap post4Bitmap(String url){
HttpPost httpPost=null;
HttpClient httpClient=null;
HttpResponse httpResponse=null;
try{
httpPost=new HttpPost(url);
httpClient=new DefaultHttpClient();
httpResponse=httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode()==200){
InputStream is=httpResponse.getEntity().getContent();
return FormatTools.getInstance().InputStream2Bitmap(is);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 异步http请求获取Json类型的返回值
* @return
*/
public JSON request4Json(Context c,JSON json){
context=c;
AsyncHttpClient client=new AsyncHttpClient();
try{
StringEntity stringEntity = new StringEntity(json.toString());
client.post(context, "http://192.4.200.29/testxr/Home/TestReq", stringEntity, "application/json", new JsonHttpResponseHandler(){
@Override
public void onSuccess(JSONObject response) {
super.onSuccess(response);
if(response.toString()!=null){
Toast.makeText(context, response.toString(), 1000).show();
Log.i("response", response.toString());
}else{
Log.i("response", "请求错误");
}
}
});
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
// 格式转换类
public class FormatTools {
private static FormatTools tools = new FormatTools();
private FormatTools() {
}
public static FormatTools getInstance() {
if (tools == null) {
tools = new FormatTools();
return tools;
}
return tools;
}
// 将byte[]转换成InputStream
public InputStream Byte2InputStream(byte[] b) {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
return bais;
}
// 将InputStream转换成byte[]
public byte[] InputStream2Bytes(InputStream is) {
String str = "";
byte[] readByte = new byte[1024];
int readCount = -1;
try {
while ((readCount = is.read(readByte, 0, 1024)) != -1) {
str += new String(readByte).trim();
}
return str.getBytes();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 将Bitmap转换成InputStream
public InputStream Bitmap2InputStream(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
// 将Bitmap转换成InputStream
public InputStream Bitmap2InputStream(Bitmap bm, int quality) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
// 将InputStream转换成Bitmap
public Bitmap InputStream2Bitmap(InputStream is) {
return BitmapFactory.decodeStream(is);
}
// Drawable转换成InputStream
public InputStream Drawable2InputStream(Drawable d) {
Bitmap bitmap = this.drawable2Bitmap(d);
return this.Bitmap2InputStream(bitmap);
}
// InputStream转换成Drawable
public Drawable InputStream2Drawable(InputStream is) {
Bitmap bitmap = this.InputStream2Bitmap(is);
return this.bitmap2Drawable(bitmap);
}
// Drawable转换成byte[]
public byte[] Drawable2Bytes(Drawable d) {
Bitmap bitmap = this.drawable2Bitmap(d);
return this.Bitmap2Bytes(bitmap);
}
// byte[]转换成Drawable
public Drawable Bytes2Drawable(byte[] b) {
Bitmap bitmap = this.Bytes2Bitmap(b);
return this.bitmap2Drawable(bitmap);
}
// Bitmap转换成byte[]
public byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
// byte[]转换成Bitmap
public Bitmap Bytes2Bitmap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
return null;
}
// Drawable转换成Bitmap
public Bitmap drawable2Bitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
// Bitmap转换成Drawable
public Drawable bitmap2Drawable(Bitmap bitmap) {
BitmapDrawable bd = new BitmapDrawable(bitmap);
Drawable d = (Drawable) bd;
return d;
}
}
Android HttpClient GET或者POST请求基本使用方法
在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求(它的功能远不止这些,这里只介绍如何使用HttpClient发起GET或者POST请求)
GET 方式
//先将参数放入List,再对参数进行URL编码
List params = new LinkedList();
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();
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, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "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 post请求
HttpPost httpPost = new HttpPost(url);List<NameValuePair> params = new ArrayList<NameValuePair>();
try {
params.add(new BasicNameValuePair("data", getUserPhoneDataInfo().toString()));---------- BasicNameValuePair不能传字符串
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = new DefaultHttpClient().execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
System.out.println("Response" + result);
} else {
System.out.println("Error Response" + response.getStatusLine().toString());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
getUserPhoneDataInfo()是我自己定义的一个JSONArray数组
怎么进行请求 试了好几种方式!都不行!
log提示请求的是一个字符串而后台接收的是一个array 该怎么修改!
Android studio使用OKGO的POST请求访问http失败的解决方法
前几天在旧手机(版本是Android7)上调试一个app,用OKGO的post请求连接服务器登录一直很正常。今天旧手机不在身边,用自己的手机调试,就出现网络请求失败的问题,弹onError()里自己写的Toast提示。反复检查了手机确实没有对app关闭网络权限,USB调试都打开了。于是在网上搜索了一些方法,尝试后问题得到解决。在这记录一下这两种解决方案。
1.targetSdkVersion 降到27以下
在build.gradle中把targetSdkVersion版本从30降为27以下(也就是Android8.0以下),Sync Now一下或者在File中点击Sync project with Gradle files同步引用库,再重新启动app,发现网络请求可以了,问题解决。
2.允许http请求
也可以选择不降targetSdkVersion版本,直接在 res 下新增一个 xml 文件,创建一个名为:network_security_config.xml 文件(名字随便起),内容是:
<?xml version="1.0" encoding="utf-8"?> <!--Android9以上机型 https请求适配--> <network-security-config> base-config cleartextTrafficPermitted="true" /> </>
然后在AndroidManifest.xml文件下的application标签增加属性
android:networkSecurityConfig="@xml/network_security_config
实例如下图所示:
application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher_round" android:label="@string/app_name" android:roundIcon android:supportsRtl android:theme="@style/AppTheme" android:networkSecurityConfig="@xml/network_security_config"> activity =".LoginActivity"> intent-filter> action ="android.intent.action.MAIN" /> category ="android.intent.category.LAUNCHER" /> activity=".HomeActivity"></application>
再次运行程序,网络请求成功,问题解决。
3.引起问题的原因
在Android 8加强了系统安全权限之后,Android P 又限制了明文流量的网络请求,非加密的流量请求都会被系统直接禁止掉,目前网络访问基本都从原来的http替换成https也是为了加强安全性。如果当前应用的请求是 HTTP 请求,而非 HTTPS,这样系统就会禁止当前应用进行该请求,如果 WebView 的 URL 用 HTTP 协议,同样会出现加载失败,将无法显示WebView的内容,HTTPS 则不受影响。
今天关于Android,Java:HTTP POST请求和android handler post的讲解已经结束,谢谢您的阅读,如果想了解更多关于android http post 请求获取 json 图片、Android HttpClient GET或者POST请求基本使用方法、Android post请求、Android studio使用OKGO的POST请求访问http失败的解决方法的相关知识,请在本站搜索。
本文标签: