0
点赞
收藏
分享

微信扫一扫

Android Http协议(post get)

科牛 2023-02-25 阅读 21


在开发android的app的时候,经常会用到http 请求,一下是post方法和get方法

<span style="font-size:14px;">
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpUtils {
private static HttpUtils httpUtils;
public static HttpUtils getInstance(){
if(httpUtils == null)
httpUtils = new HttpUtils();
return httpUtils;
}

/*
* Post请求
* @urlParameters 请求URL
*/
public String httpPostRequest(String urlParameters, String uname,String pwd){
String result = "";
try {
HttpPost httpPost = new HttpPost(urlParameters);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("UserName", uname));
params.add(new BasicNameValuePair("Passwords", pwd));
HttpEntity httpEntity = new UrlEncodedFormEntity(params,"UTF-8");
httpPost.setEntity(httpEntity);

HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
result = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
result = "";
}
} catch (Exception e) {
result = "";
}
return result;
}

public String httpGetRequest(String urlParameter){
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urlParameter);
HttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200) {
result = getResponseToString(response.getEntity().getContent());
}
}catch(Exception e){
result = "";
}
return result;
}


private String getResponseToString(InputStream inputStream) {
String result = "";
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i = 0;
byte[] buf = new byte[1024];
while((i = inputStream.read(buf)) != 0){
byteArrayOutputStream.write(i);
}
result = new String(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
</span>



举报

相关推荐

0 条评论