android 用JSON去服务器获取JSON对象 和其他的几种方法去服务器获取JSON对象

来源:互联网 发布:爱剪辑软件下载 编辑:程序博客网 时间:2024/05/21 10:32

由于工作需要     查看了关于这方面的资料  写了一个dome   现在分享给大家

我用了三种往服务器传值的方法获取JSON对象


第一种 往服务器传Map键值对 的方式

import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import java.util.Map;import org.json.JSONException;import org.json.JSONObject;import android.util.Log;public class HttpPostUtils {private static JSONObject json=null;/** *  * @param params * 上传参数 * @param encode * 字节编码 * @param path * 路径 * @return * */public static JSONObject sendPostMessage(Map<String,String> params,String encode,String path){URL url=null;try {url=new URL(path);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}//作为StringBuffer初始化的字符串StringBuffer buffer = new StringBuffer();if(params != null && !params.isEmpty()){for(Map.Entry<String, String> entry:params.entrySet()){//完成转码操作try {buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//删除掉最后一个&buffer.deleteCharAt(buffer.length()-1);}Log.e("."+buffer, "_");try {HttpURLConnection conn=(HttpURLConnection) url.openConnection();conn.setConnectTimeout(3000);//连接超时时间我设为3秒conn.setRequestMethod("POST");//用那post 或者get//表示从服务器获取数据conn.setDoInput(true);//表示向服务器写数据conn.setDoOutput(true);//获得上传信息的字节大小以及长度byte[] data = buffer.toString().getBytes();//表示设置请求体的类型是文本类型conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", String.valueOf(data.length));//获得输出流,向服务器输出数据OutputStream os = conn.getOutputStream();os.write(data,0,data.length);os.flush();os.close();//获得服务器响应的结果和状态码int code = conn.getResponseCode();if(code == 200){String aa=changeInputStream(conn.getInputStream(), encode);json=new JSONObject(aa);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} return json;}private static String changeInputStream(InputStream inputStream,String encode){ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] data=new byte[1024];int len = 0;String result = "";if(inputStream!=null){try {while((len = inputStream.read(data))!=-1){output.write(data,0,len);}result =new String(output.toByteArray(),encode);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}}


第二种 用JSON对象从服务器获取JSON对象



import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.List;import org.json.JSONException;import org.json.JSONObject;import android.util.Log;public class HttpUtils {/**第一个参数是 路径*第二个参数是 要传到服务器的JSON对象*/public static JSONObject sendHttpClientPost(String path, JSONObject params) {URL url;JSONObject jsonObject=null;try {url=new URL(path);//把已经封装好的数据传递到服务器HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置相应超时时间conn.setConnectTimeout(5000);//打开输出流,以便向服务器提交数据conn.setDoOutput(true);//打开输入流,以便从服务器获取数据conn.setDoInput(true); //使用Post方式不能使用缓存conn.setUseCaches(false);conn.setRequestMethod("POST");// 设置发送数据的格式  conn.setRequestProperty("Content-Type", "application/json");conn.connect();DataOutputStream out = new DataOutputStream(conn.getOutputStream()); //把JSON数据转换成String类型使用输出流向服务器写String content = String.valueOf(params);out.writeBytes(content);out.flush();out.close();int code = conn.getResponseCode();if(code == 200){InputStream is = conn.getInputStream();String json = NetUtils.readString(is);jsonObject=new JSONObject(json);}Log.e("鏈接失败", "_");} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}return jsonObject;}}

用于解析从服务器获取的输入流

import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class NetUtils {//用于解析输入流的public static byte[] readBytes(InputStream is){byte[] buffer = new byte[1024];int len=-1;ByteArrayOutputStream baos = new ByteArrayOutputStream();try {while((len = is.read(buffer))!=-1){baos.write(buffer,0,len);}baos.close();return baos.toByteArray();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}public static String readString(InputStream is){return new String(readBytes(is));}}


第三种用HttpPost类访问服务器获取数据

import java.io.IOException;import java.io.UnsupportedEncodingException;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicHeader;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import org.json.JSONException;import org.json.JSONObject;public class HttpPostaa {/**第一个参数是 路径*第二个参数是  JSON对象*/public static JSONObject sendHttpClientPost(String path,JSONObject params){try {StringEntity se = new StringEntity(params.toString());se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));HttpPost request=new HttpPost(path);request.setEntity(se);HttpResponse respose = new DefaultHttpClient().execute(request);String retSrc = EntityUtils.toString(respose.getEntity());JSONObject result = new JSONObject(retSrc);return result;} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}

这几种方法第一种比较常用     还有几种还没写  有空的话或写上来的

转载时请转载注明转载地址:http://blog.csdn.net/u014451709/article/details/40504039

0 0
原创粉丝点击